Search code examples
matlabbitmapexportshapesrasterize

Export/Rasterize alpha shape to bitmap


I build an alpha shape from some points (example given in code) and want to export the shape to a raster graphics format. I need the shape only, not the plot markings (axis, scales ect).

I need only the resulting triangle on white ground as a bitmap. Scale needs to be 1 unit = 1 pixel.

x = [0 10 20 30 30 30 15];
y = [0 0 0 0 15 30 15];

shape = alphaShape (x',y');

plot (shape, 'FaceColor', 'black');

alpha shape plotted

I have not found anything on how to export shapes or how to rasterize them. Is there any way to do that?


Solution

  • Run the following code after yours.

    imgwidth = max(1, ceil(max(x) - min(x)));
    imgheight = max(1, ceil(max(y) - min(y)));
    ax = gca;
    ax.Visible = 'off';
    ax.XTickMode = 'manual';
    ax.YTickMode = 'manual';
    ax.ZTickMode = 'manual';
    ax.XLimMode = 'manual';
    ax.YLimMode = 'manual';
    ax.ZLimMode = 'manual';
    ax.Position = ax.OuterPosition;
    af = gcf;
    figpos = getpixelposition(af);
    resolution=get(0, 'ScreenPixelsPerInch');
    set(af, 'paperunits','inches', ....
        'papersize',[imgwidth imgheight]/resolution, ....
        'paperposition',[0 0 [imgwidth imgheight]/resolution]);
    print(af,'out.png','-dpng',['-r',num2str(resolution)],'-opengl')
    

    Things done:

    • Fetch data range and convert to image dimensions.
    • Turn off axes and ticks.
    • Minimize/remove padding space surrounding the actual content.
    • Map 1 unit in data into 1 pixel in output image.

    Things not done:

    • Guarantee aspect ratio. (should work, though)

    This screenshot shows non-unity aspect ratio output:

    example screenshot

    References

    Mathworks - Save Figure at Specific Size and Resolution

    MATLAB Central - saving a figure at a set resolution

    Mathworks - print

    Mathworks - Save Figure with Minimal White Space