Function Repository Resource:

AspectRatioImagePad

Source Notebook

Pad an image so its aspect ratio approximates a specified value

Contributed by: Phileas Dazeley-Gaist

ResourceFunction["AspectRatioImagePad"][image,ratio]

pads image with black pixels so its aspect ratio approximates ratio.

ResourceFunction["AspectRatioImagePad"][image]

uses an aspect ratio of 1.

ResourceFunction["AspectRatioImagePad"][image,ratio,padding]

pads image so its aspect ratio approximates ratio with the value or method specified by padding.

Details

ResourceFunction["AspectRatioImagePad"] pads image with the minimum number of pixels, equally distributed between padding sides, to result in an image with the approximate aspect ratio ratio.
ResourceFunction["AspectRatioImagePad"] accepts all valid ImagePad padding specifications for the value of padding.
ResourceFunction["AspectRatioImagePad"] will never crop an image.
ResourceFunction["AspectRatioImagePad"][image,Automatic,padding] is equivalent to ResourceFunction["AspectRatioImagePad"][image,1,padding].

Examples

Basic Examples (3) 

Pad an image to make it square:

In[1]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/c4de8004-a2db-4f82-b37f-d63faad8cd02"]
Out[1]=

Measure the aspect ratio of the new image:

In[2]:=
N@ImageAspectRatio[image]
Out[2]=

Pad an image to a specific aspect ratio:

In[3]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/a6a4f182-9f43-4233-b100-575c49214696"]
Out[3]=

Pad using the "TextureSynthesis" padding scheme:

In[4]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/2379f283-8dc3-40cd-8e6f-66822da5f169"]
Out[4]=

Possible Issues (1) 

For very small images, where adding rows or columns of pixels accounts for relatively large changes in the aspect ratio of the resulting image, the function may fail to apply appropriate padding:

In[5]:=
image = RandomImage[{0, 1}, {5, 4}, ColorSpace -> "RGB"]
Out[5]=
In[6]:=
ResourceFunction["AspectRatioImagePad"][image]
Out[6]=

Neat Examples (1) 

Use AspectRatioImagePad for art by nestedly applying a function to a starting image that pads it to a goal ratio, then inverts the image, and pads it with one column or row of white pixels on each side:

In[7]:=
Nest[
   ImagePad[ColorNegate[
      ResourceFunction["AspectRatioImagePad"][#1, RandomReal[{.7, 1.3}], "Reflected"]
      ], 1, 1] &,
   Image[DiskMatrix[5]], 20] // MorphologicalComponents // Colorize[#, ColorFunction -> "CMYKColors"] &
Out[7]=

Publisher

Phileas Dazeley-Gaist

Requirements

Wolfram Language 14.0 (January 2024) or above

Version History

  • 1.0.0 – 11 December 2024

Related Resources

License Information