Ryan Nel
Ryan Nel

Reputation: 464

Julia-Lang: Square an image with a fixed background colour

I have a series of images of different sizes.

x x x x
x x x x
x x x x

I would like to convert these to be square with a set fill colour in order to maintain aspect ratio.

x x x x
x x x x
x x x x
0 0 0 0

Is there any way to do this in Juila, preferably using the Images.jl package.

Upvotes: 2

Views: 95

Answers (1)

ntdef
ntdef

Reputation: 504

Assuming that you want to always up-broadcast the number of rows to square your image, the following function will get you what you need.

using Images, Colors

function square_up(image; value=RGB(0.,0.,0.))
    A = data(image)
    nrows, ncols = size(A)
    fill_in_mat = fill(value, (ncols-nrows, ncols))
    new_A = vcat(A, fill_in_mat)
    new_image = copyproperties(image, new_A)
    return new_image
end

Using a test image as an example:

using TestImages

img = testimage("mandrill")
# Cut the bottom half out of the image
A = data(img)
println(size(A))
B = A[1:floor(size(A, 1)/2.),:]
B_image = copyproperties(img, B)

# Apply the function to get new image filled with `value`
# The default is to fill with RGB(0,0,0)
out_image = square_up(B_image)

# Check that its square
println(size(out_image, 1) == size(out_image, 2))

To set the fill color, just mess with the value parameter.

Upvotes: 4

Related Questions