Skip to content

Arithmetic operations

kkrmno edited this page Mar 19, 2020 · 6 revisions

Difference between two images

Image credit: NASA


To find the difference between two images, one may simply subtract one from the other, yielding:

image_before = Imgrb::Image.new("nasa_flooding_before.png")
image_after = Imgrb::Image.new("nasa_flooding_after.png")

#Find the absolute (pixelwise) difference between the two images
image_diff = (image_after - image_before).abs
image_diff.save("nasa_flooding_diff.png")

Product of two images

Similarly, one may take the product of two images img0 and img1

img0 * img1

As an example, this can be used to mask out a part of an image:

#Create a circular mask
circle_mask = Imgrb::Image.new(image_after.width, image_after.height, [0,0,0])
center_x = 200
center_y = 300
radius = 100
circle_mask.width.times do
  |x|
  circle_mask.height.times do
    |y|
    dx = center_x - x
    dy = center_y - y
    dist = Math.sqrt(dx*dx + dy*dy)
    if dist <= radius
      circle_mask.set_pixel(x,y,[1,1,1])
    end
  end
end

#Apply the mask, keeping everything inside the circle, setting everything outside it to 0.
masked_image = image_after * circle_mask
masked_image.save("circle_masked.png")

Other operations

Similarly one may divide, and add pairs of images. It is also possible to raise one to the power of another (pixelwise), using **. One may also add, subtract, multiply, divide, and raise to a power where the second argument is a scalar, e.g.

img * 2 #Multiplies pixels by 2

#Divides pixels by 2.0.
img / 2.0
#This creates a new image with floating point values, these should be dealt with before
#saving, by for example rounding to the nearest integer values, i.e.:
(img / 2.0).round

#Adds 10 to pixels
img + 10

#Subtracts 10
img - 10

#Takes the square root of all values
img ** 0.5
Note that there are no checks to see if pixel values belong to the set of allowed values for any given image format you may want to save to, so take care that the final values of your image belong to the allowed set before saving.