# Set pixel aspect ratio?

Bug partially fixed in 12.1 [CASE:4081592]
ImageResolution now works correctly for Image, but not for Image3D.

Does Mathematica have a feature to set the pixel aspect ratio of 2D images?

For example,

Image3DSlices[ExampleData[{"TestImage3D", "CThead"}], 100, 3]


I can resize this to the correct aspect ratio, like so:

But I do not want to modify the data. I just want to control how it is displayed. With 3D images, we can use BoxRatios. What about 2D?

• Something like Graphics[Raster[ImageData[img, DataReversed -> True]], AspectRatio -> 1]?
– chuy
Jun 21 '18 at 18:51
• You can use Show with the AspectRatio->1, but the image quality is much lower. Or something like this: ImageResize[yourimage, {#, #} &@Max@ImageDimensions[yourimage]]. I work with images quite often but I don't know an option like BoxRatios that work with image objects. Jun 21 '18 at 18:54
• From Filling a rectangle with an image: VertexTextureCoordinates looks like it could work. e.g. Graphics[{Texture[img], Polygon[{{0, 0}, {0, y}, {x, y}, {x, 0}}, VertexTextureCoordinates -> {{0, 0}, {0, 1}, {1, 1}, {1, 0}}]}] But it is quite verbose. I'm pretty sure there is an elegant way to convert an Image into a Graphics object. Jun 21 '18 at 23:02
• @JungHwanMin Pre 11.0 or something Rasterize returned a Graphics object. You could see what format it used and try that. That could then of course take a direct AspectRatio, but I can’t try this right now. Jun 22 '18 at 2:32
• @b3m2a1 Head[Rasterize[img]] returns Image, so it's no good. Jun 22 '18 at 5:34

Alexey suggested that the following undocumented (but not going away) ImageSize syntax could be used:

img = Image3DSlices[ExampleData[{"TestImage3D","CThead"}],100,3];
Show[img, ImageSize -> 1 -> {1,2}]


I think this does what you want?

• Instead of Show, we could also use Image. One issue is that when resizing with the mouse, the aspect ratio jumps back to how it was. Where did Alexey show this syntax? Oct 7 '18 at 19:03
• @Szabolcs In a comment to my answer to a similar question, Alexey suggested that the same method might be useful for this question. Oct 7 '18 at 19:06

## UPDATE

In version 12.1 they implemented correct handling of the ImageResolution option for Image (but for Image3D ImageResolution is still ignored).

Note: I've sent a suggestion for improvement to the tech support with a link to this post ([CASE:4081592]).

Mathematica already basically supports different resolutions in different directions for Image when importing and exporting (what is documented, for example, on the Documentation page for "JPEG" format):

Options[img = Import["ExampleData/coneflower.jpg",
ImageResolution -> {72, 144}], ImageResolution]

Options[Import@Export["coneflower_new.jpg", img], ImageResolution]

{ImageResolution -> {72, 144}}

{ImageResolution -> {72, 144}}


So halirutan is right: the developers just overlooked that this should also influence how the image is rendered by the FrontEnd. Other picture viewers respect this setting, for example here is how Windows Photo Viewer renders the image "coneflower_new.jpg":

As one can see from the screenshot, the image is scaled up two times in horizontal direction according to the specified ImageResolution which is two times smaller in horizontal direction (72 dpi) than in vertical direction (144 dpi), as expected.

But I think that it is incorrect to set AspectRatio of the whole image equal to pixel aspect ratio (as halirutan did), because we should also take into account actual ImageDimensions when calculating the overall AspectRatio. So here is my fix for Image which makes it respecting the ImageResolution setting (I wrapped changed portions of the original code by (* edit start *) and (* edit end *) tags):

Unprotect[Image];
MakeBoxes[ImageImageDumpimg : Image[_, ImageImageDumptype_, ImageImageDumpinfo___],
ImageImageDumpfmt_] /; ImageValidImageQHold[ImageImageDumpimg] ^:= With[{
ImageImageDumpnewarray =
ImageInternalImageData[ImageImageDumpimg, Interleaving -> True],
ImageImageDumptag =
BoxFormImageTag[ImageImageDumptype,
Sequence @@
FilterRules[FilterRules[{ImageImageDumpinfo}, Except[Options["Graphics"]]],
Except[ImageMarkers]]],
ImageImageDumpimgdata =
ImageData[ImageImageDumpimg, {"Width", "Height", "DataRange", "ColorFunction"}],
ImageImageDumpimgsize =
ImageImageDumpruleValue[{ImageImageDumpinfo}, ImageSize],
ImageImageDumpmag =
ImageImageDumpruleValue[{ImageImageDumpinfo}, Magnification],
(* edit start *)
ImageImageDumppixelAspectRatio =
With[{ImageImageDumpres =
ImageImageDumpruleValue[{ImageImageDumpinfo}, ImageResolution]},
If[MatchQ[ImageImageDumpres, {_?(# > 0 &), _?(# > 0 &)}],
Divide @@ ImageImageDumpres, 1, 1]
]
(* edit end *)
},
With[{
(* edit start *)
ImageImageDumpwidth =
ImageImageDumpimgdata[[1]]/
If[ImageImageDumppixelAspectRatio < 1, ImageImageDumppixelAspectRatio, 1, 1],
ImageImageDumpheight =
ImageImageDumpimgdata[[2]]*
If[ImageImageDumppixelAspectRatio > 1, ImageImageDumppixelAspectRatio, 1, 1],
(* edit end *)
ImageImageDumprange = ImageImageDumpimgdata[[3]],
ImageImageDumpcfun = ImageImageDumpimgdata[[4]]},
With[{ImageImageDumpoptions = Sequence @@ Join[{
DefaultBaseStyle -> "ImageGraphics",
ImageSizeRaw -> {ImageImageDumpwidth, ImageImageDumpheight},
PlotRange -> {{0, ImageImageDumpwidth}, {0, ImageImageDumpheight}}
},
ImageImageDumpConvertImageSizeToFE[ImageImageDumpimgsize,
ImageImageDumpmag],
FilterRules[{ImageImageDumpinfo}, ImageImageDump\$typesetOptions]]},
GraphicsBox[
TagBox[RasterBox[
ImageImageDumpnewarray, {{0, ImageImageDumpheight}, {ImageImageDumpwidth,
0}}, ImageImageDumprange, ColorFunction -> ImageImageDumpcfun],
ImageImageDumptag, Selectable -> False], ImageImageDumpoptions]]]];
Protect[Image];


Now

Import["coneflower_new.jpg"]


Image[Image3DSlices[ExampleData[{"TestImage3D", "CThead"}], 100, 3],
ImageResolution -> {72, 72/2}]


• Yes, you are absolutely right. I was sloppy in my implementation. The displayed size of the image should take the resolution as an indicator of what aspect ratio one pixel has. I have described it correctly, but my implementation does not reflect this. When you get an answer from Wolfram, would you update Szabolcs question with the bug-head and tag it as bugs? Jun 26 '18 at 14:15
• @halirutan Yes, I'll update the answer (and the question if relevant) with responce from the support when I receive it. Jun 26 '18 at 15:09
• @halirutan I've received a responce: "I have passed along a report to our developers on this suggestion." If something more informative will come, I'll post an update. Jun 27 '18 at 7:31
• @halirutan They fixed this bug for Image in version 12.1 (but not for Image3D). Mar 19 '20 at 12:45

This might have been overlooked in the implementation of Image. When I see this right, then the correct way to handle this would be to respect the setting of ImageResolution and acknowledge that it can be different for different directions

and it is not unusual for medical devices like a CT to have a drastic difference in resolution for different directions. For a plain image, that doesn't know its resolution, the displayed size is always determined by assuming pixels are squares and using the ImageDimension-ratio as aspect-ratio.

However, I would have expected that something like this works

img = Image3DSlices[ExampleData[{"TestImage3D", "CThead"}], 100, 3];
Image[img, ImageResolution -> {100, 100}]


Unfortunately it doesn't, although the GraphicsBox would support it. But we could fix MakeBoxes for Image and we would get

Below are the changes I made as an image because it seems not easily possible to copy code from the PrintDefinitions view.

It is indeed surprisingly difficult. We have to set explicit AspectRatio and ImageSize (and optionally Magnification) after conversion into the corresponding Graphics object:

pixelAspectRatio = 2;
img = Image3DSlices[ExampleData[{"TestImage3D", "CThead"}], 100, 3];

Show[img,
AspectRatio -> pixelAspectRatio*ImageAspectRatio[img],
ImageSize -> ImageDimensions[img]*{1, pixelAspectRatio}
(*, BaseStyle -> Magnification -> 1*)]


Other options:

Show[img, PlotRange -> All, PlotRangePadding -> None,
ImageSize -> ImageDimensions[img]*{1, pixelAspectRatio}
(*, BaseStyle -> Magnification -> 1*)] /.
r_Raster :> Scale[r, {1, pixelAspectRatio}]

With[{is = ImageDimensions[img]*{1, pixelAspectRatio}},
Show[img, PlotRange -> All, PlotRangePadding -> None, ImageSize -> is
(*, BaseStyle -> Magnification -> 1*)] /.
Raster[array_, _, opts___] :> Raster[array, {{0, 0}, is}, opts]]


We can avoid conversion into a Graphics object by using Style for changing the default options of GraphicsBox locally. Unfortunately via GraphicsBoxOptions we can't change ImageSize stored in the Image object itself, hence we should change it directly via Image:

Style[Image[img, ImageSize -> ImageDimensions[img]*{1, pixelAspectRatio}],
GraphicsBoxOptions ->
{AspectRatio -> pixelAspectRatio*ImageAspectRatio[img]
(*, BaseStyle -> Magnification -> 1*)}]


ImageSize -> All also works:

Style[Image[img, ImageSize -> All], GraphicsBoxOptions ->
{AspectRatio -> pixelAspectRatio*ImageAspectRatio[img]
(*, BaseStyle -> Magnification -> 1*)}]


We can prove that the displayed size is indeed correct by rasterizing the output and taking its "RasterSize":

ImageDimensions[img]
Rasterize[PreviousCell[], "RasterSize"]

{256, 99}

{256, 198}


• +1 for the info that Style can be used. I looked through the complete MakeBoxes of Image to see if I can somehow inject this option so that you don't have either fix the code or use a wrapper like Style. Seems not possible with Image` alone. Jun 22 '18 at 22:27