I am looking to generate image masks using Graphics
. For this, the requirements are that:
- The rasterized mask must have the exact same dimensions as the image with which it will be used.
- The image coordinates system (as described in the documentation of
ImageValue
, under Details) must line up perfectly with theGraphics
coordinate system.
Neither seems to work readily.
Mask has an incorrect size
dims = {20, 20};
mask = Rasterize[
Graphics[{},
PlotRange -> Transpose[{{0, 0}, dims}], ImageSize -> dims,
PlotRangePadding -> None
],
ImageResolution -> 72
]
The mask
is of the wrong size. ImageDimensions[mask]
gives {20, 22}
.
Coordinates don't line up
Example code:
dims = {21, 21};
pix = Image@ReplacePart[ConstantArray[0, dims], {{11, 11}} -> 1]
mask = Rasterize[
Graphics[{Disk[dims/2, 6]},
PlotRange -> Transpose[{{0, 0}, dims}], ImageSize -> dims,
PlotRangePadding -> None
],
ImageResolution -> 72
]
The image size is odd, so there is a middle pixel. pix
visualizes this pixel. mask
draws a disk around it. But the pixel is clearly not in the middle of the disk:
Magnify[mask + pix, 5]
Attempted workarounds
ImageMargins -> 0, ImagePadding -> None
does not help.- Adding
ImageSize
toRasterize
as well, in addition toGraphics
, does not help. RasterSize
can force a specific image size, but it does not help with alignment
System information
Mathematica 13.0.1, macOS 10.14.6 (Mojave), and a retina screen
RasterSize -> dims
instead? ImageSize for Rasterize is only the display dimensions… $\endgroup$RasterSize
. I suspect what it does is a rescaling after creating an image. TheImageSize
and theImageResolution
together should give a good result. The reason why I worry about such rescaling is that it might mess up the alignment between the image coordinates and the graphics coordinates. $\endgroup$RegionImage
be of use? $\endgroup$