-
Notifications
You must be signed in to change notification settings - Fork 0
Resizing Images
Using resize
, one may change the size of images:
require 'imgrb'
img = Imgrb::Image.new("MET_music_lesson_cropped.png")
#Create a resized image a quarter of the size of the original using bilinear interpolation
img_resized = img.resize(0.25)
img_resized.save("MET_music_lesson_resized.png")
"The Music Lesson" by Chelsea Porcelain Manufactory from the collection of the Metropolitan Museum of Art is licensed under CC0 1.0.
It is also possible to scale different amounts horizontally and vertically by giving two parameters to resize
:
img.resize(0.5, 1.5) #Halves the width of the image and increases the height by 50 percent.
By default, resize
uses bilinear interpolation. If desired, one may choose nearest neighbor interpolation instead:
img.resize(scale_x, scale_y, :nearest)
Note that the resize method (currently) does not perform any antialiasing. This can cause problems when scaling images down. To illustrate this, the following test pattern is used and rescaled:
Generated by the following piece of code:
#See https://blogs.mathworks.com/steve/2011/07/16/jahne-test-pattern/
def test_pattern(km, sz)
sz = sz.ceil
rm2 = 2*Math.sqrt(2*sz**2)
img = Imgrb::Image.new(sz*2+1, sz*2+1, 0)
img.height.times do |y|
img.width.times do |x|
x_ = x - sz
y_ = y - sz
d = x_**2 + y_**2
val = 0.5*(Math.sin(km*d/rm2) + 1)*255
img.set_pixel(x,y,val.round)
end
end
return img
end
test_image = test_pattern(Math::PI/1.5, 256)
Resizing by calling img.resize(0.25)
yields the following image showing aliasing:
One simple way of dealing with this issue is to blur the image (i.e. lowpass filter) before resizing:
test_image_blurred = test_image.blur(2).round #Gaussian blur with sigma = 2
test_image_halved_aa = test_image_blurred.resize(0.25)
test_image_halved_aa.save("test_image_res_aa.png")