# Grid shows next to image, not on actual image, and ImageDimensions are wrong. What can I do?

I am still using Mathematica 10.3 and I have the following problem:

My code is as follows (based on what I found in a related post, see below), but I used another example image. So here is my code:

 img = ExampleData[{"AerialImage", "Pentagon"}];

grid = Graphics[{}, GridLines -> Automatic, PlotRangePadding -> None,
GridLinesStyle -> Directive[Red, Thick],
ImageSize -> ImageDimensions@img];

Overlay[{img, grid}];


The output is completely off -- the grid is much larger than the image. I also tried with an actual image I am interested in, and that gave me the same problem. It does work fine with test image "Lena", but not with any other image.

However, if I check ImageDimensions[img] and ImageDimensions[grid], I do get the same output. So it might just be that for some reasons, all other images except for "Lena"give me a wrong output concerning the ImageDimensions, which is why the grid might be messed up.

Can anyone help with this? What can I do?

P.S. My question is related to and my code is based on the question and answers here: Image with grid lines

• try Overlay[{Show[img, ImageSize -> ImageDimensions@img], grid}]?
– kglr
Jan 29 '21 at 9:25
• try also the methods in this answer
– kglr
Jan 29 '21 at 9:27
• Hi, Thanks so much! Yeah, the other methods mentioned in the post you linked are the ones I read first. However, your suggestion is already very helpful. My code now looks like this: n = 25; m = 25; sub1 = Subdivide[-1, 1, n]; sub2 = Subdivide[-1, 1, m]; grid = Graphics[{}, GridLines -> {sub1, sub2}, PlotRangePadding -> None, GridLinesStyle -> Directive[Red, Thick], ImageSize -> ImageDimensions@img]; Overlay[{Show[img, ImageSize -> ImageDimensions@img], grid}] Jan 29 '21 at 13:06
• This seems to work only for square images, though. My image is not square. Even if I change m and n, the grid will only appear in the middle of the image and it will be a square, even if the small grids are rectangles. How can I make sure the grid covers the entire image, not only the middle? Jan 29 '21 at 13:08
– kglr
Jan 29 '21 at 13:45

n = 10; m = 10;

img1 = ImageResize[img, {500, 500}];

id1 = ImageDimensions@img1;

gridlinesx1 = Subdivide[1, id1[[1]], n];
gridlinesy1 = Subdivide[1, id1[[2]], m];

grid1 = Graphics[{}, GridLines -> {gridlinesx1, gridlinesy1},
PlotRange -> prange1, PlotRangePadding -> None,
GridLinesStyle -> Directive[Red, Thick], ImageSize -> id1];
Overlay[{Show[img1, ImageSize -> id1], grid1}]


Use m = 5 to get

The same approach works for a non-square image:

n = 10; m = 10;
img2 = ImageResize[img, {500, 300}];

id2 = ImageDimensions@img2;

gridlinesx2 = Subdivide[1, id2[[1]], n];
gridlinesy2 = Subdivide[1, id2[[2]], m];


and with m = 5: