I used in my calculations zome polynomials evaluated on a grid with Array
command and characteristic functions of some polygons, which I evaluated using Rasterize
function and I realised that the results of these two sampling paradigms are not consistent. It looks like Rasterize
ignores or adjusts the PlotRange
option. The best it can be illustrated by this MWE:
Manipulate[
graphics =
Graphics[{GrayLevel[0], Disk[{0, 0}, .8]},
PlotRange -> {{-1, 1}, {-1, 1}}, Frame -> True];
raster =
Rasterize[
Graphics[{GrayLevel[0], Disk[{0, 0}, .8]},
PlotRange -> {{-1, 1}, {-1, 1}}],
RasterSize -> {picsize, picsize},
ImageSize -> {picsize, picsize}];
array =
Image @ Boole @
Array[{##} ∉ Disk[{0, 0}, .8] &, {picsize, picsize}, {{-1, 1}, {-1, 1}}];
Grid[
{{"Graphics", "Rasterize", "Array", "Rasterize vs Array"},
Show[#, ImageSize -> 200, Frame -> True] & /@
{graphics, raster, array, ColorCombine[{raster, array, array}]}}],
{{picsize, 15}, 3, 50, 1}]
In this example, where a disk with a radius of 0.8 is shown in a square region [-1, 1]^2, it's visible that while Graphics
and Array
show nicely centred disk independently of the spatial sampling rate, Rasterize
behaves weird.
The figure below shows the graphics object and its sampled versions as calculated by Rasterize
and Array
(Mathematica 12.1, Windows 10). The last plot overlays the two representations for comparison, so the misalignment is visible.
Is it a bug or do I miss something?
The reason I use Rasterize
and not Array
that Rasterize
is much faster for large image sizes.
Update and Workaround: the misalignment can be corrected by changing the plot region by adding to it right and top margins of one pixel width. In the example above, for instance, the perfect alignment can be obtained by using
Rasterize[
Graphics[{GrayLevel[0], Disk[{0, 0}, .8]},
PlotRange -> {{-1, 1 + 2/picsize}, {-1 - 2/picsize, 1}}],
RasterSize -> {picsize, picsize}]
So the MWE above can be modified to
Manipulate[
graphics =
Graphics[{GrayLevel[0], Disk[{0, 0}, .8]},
PlotRange -> {{-1, 1 + 2/picsize}, {-1 - 2/picsize, 1}},
GridLines -> {{-1, 0, 1}, {-1, 0, 1}}];
tr = Timing[
raster =
Rasterize[graphics, RasterSize -> {picsize, picsize}];];
tarr = Timing[
array =
Image @ Boole @
Array[{##} ∉ Disk[{0, 0}, .8] &, {picsize, picsize}, {{-1, 1}, {-1, 1}}];];
Grid[
{{"Graphics",
"Rasterize, " <> ToString[tr[[1]]] <> "s",
"Array, " <> ToString[tarr[[1]]] <> "s",
"Rasterize vs Array"},
Show[#, ImageSize -> 200, Frame -> True] & /@
{graphics, raster, array, ColorCombine[{raster, array, array}]}}],
{{picsize, 15}, 3, 50, 1}]
From all this, my guess is that Rasterize
select the sampling points uniformly in the specified plot region, and uses them as top-left corners for the pixels. Effectively, this increases the total plot region.