Image arithmetic
We are very much familiar with basic arithmetic operation like addition and subtraction. When we want to do the arithmetic to our image we should be careful about the color space and data types.
We know RGB images have pixel values fall within the range [0,255]. If we want to add 20 with our pixel intensity 250, that will cross the limit range. If we normally add that the value must be 270 but for this case more than 270 is not a valid value. You should have known by now the reason behind the limit range of 255, which represents the 8-bit unsigned integers.
So what is the right way to do arithmetic operation on image? There are actually two ways and you should be familiar with both of them. For arithmetic operation OpenCV has built in function named cv2.add. you also can perform arithmetic operation using Numpy. Numpy does modulus arithmetic and wrap around. OpenCV does clipping and make sure the pixels don’t fall outside the range of [0,255].
Let’s explore the ways using some codes
import cv2 import numpy as np image = cv2.imread('hubo.jpg',0) cv2.imshow("Original", image) print "Maximum value: " + str(cv2.add(np.uint8([200]), np.uint8([100]))) print "Minimum Value:" + str(cv2.subtract(np.uint8([50]), np.uint8([100]))) print "Wrapping around positive: " + str(np.uint8([200]) + np.uint8([100])) print "Wraping around negative: " + str(np.uint8([50]) - np.uint8([100])) One = np.ones(image.shape, dtype = "uint8") * 100 added = cv2.add(image, One) cv2.imshow("Added", added) One = np.ones(image.shape, dtype = "uint8") * 50 subtracted = cv2.subtract(image, One) cv2.imshow("Subtracted", subtracted) cv2.waitKey(0)
We tried to add using OpenCV function first and ends up at a maximum value of 255. We also did the subtraction using OpenCV function which ends up at a minimum value of 0. If it adds normally, as we are used to add numbers, the adding result would be 300 and subtraction would be -50. Let’s come to the Numpy addition and subtraction. When we added Numpy it results in 44, because it wraps in 255 and start counting from 0 after that. Since it would be 300 normally, it ends up at 44. Subtraction works at same way, it ends up at 0, which is the minimum value and start counting from backward after that. It naturally ends up at 206.
After that we declared a Numpy array of ones, with the same shape of our image. Then we added and subtracted the number of arrays from our image to see how adding and subtracting pixel looks like. The image below show the result.