In this tutorial, I will show you the Basic image Arithmetic OpenCV RaspberryPi Step By step Complet Process.

We all know basic arithmetic operations like addition and subtraction. But if working with images, we require to keep in mind the limits of our color space and data type.

For example, RGB images have pixels that fall within the range [0, 255] So what happens if we are examining a pixel with intensity 250 and we try to add 10 to it?

Below normal arithmetic rules, we would end up with a value of 260. But, since RGB images designed as 8-bit unsigned integers, 260 is not a valid value.

So, what should happen? Should we perform a check of some sort to secure no pixel falls outside the range of [0, 255], thus clipping all pixels to have a minimum value of 0 and a maximum value of 255?

Or do we use a modulus operation, and “wrap around”? Under modulus rules, adding 10 to 250 would simply wrap around to a value of 4.

Which method is the “correct” way to handle image additions and subtractions that fall outside the range of [0, 255]?

The answer is there is no correct way – it only depends on how you are manipulating your pixels and what you want the desired results to be.

But, be sure to keep in mind that there is a difference between OpenCV and NumPy addition. NumPy will work modulo arithmetic and “wrap around”. OpenCV, on the other hand, will make clipping and ensure pixel values never fall outside the range [0, 255].

**≡ Image Arithmetic OpenCV RaspberryPi Code:**

This theory is better explained through some code for writing code with raspberry pi, Fast open your command terminal on your Raspberry Pi then write this Commend:

nano

you can see like this interface

Now we can start writing This code on GNU nano:

# Import the necessary packages from __future__ import print_function import numpy as np import argparse import cv2 # Construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) # Load the image and show it image = cv2.imread(args["image"]) cv2.imshow("Original", image) # Images are NumPy arrays, stored as unsigned 8 bit integers. # What does this mean? It means that the values of our pixels # will be in the range [0, 255]. When using functions like # cv2.add and cv2.subtract, values will be clipped to this # range, even if the added or subtracted values fall outside # the range of [0, 255]. Check out an example: print("max of 255: {}".format(cv2.add(np.uint8([200]), np.uint8([100])))) print("min of 0: {}".format(cv2.subtract(np.uint8([50]), np.uint8([100])))) # NOTE: If you use NumPy arithmetic operations on these arrays, # the values will be modulos (wrap around) instead of being # clipped to the [0, 255] arrange. This is important to keep # in mind when working with images. print("wrap around: {}".format(np.uint8([200]) + np.uint8([100]))) print("wrap around: {}".format(np.uint8([50]) - np.uint8([100]))) # Let's increase the intensity of all pixels in our image # by 100. We accomplish this by constructing a NumPy array # that is the same size of our matrix (filled with ones) # and the multiplying it by 100 to create an array filled # with 100's. Then we simply add the images together. Notice # how the image is "brighter". M = np.ones(image.shape, dtype = "uint8") * 100 added = cv2.add(image, M) cv2.imshow("Added", added) # Similarly, we can subtract 50 from all pixels in our # image and make it darker: M = np.ones(image.shape, dtype = "uint8") * 50 subtracted = cv2.subtract(image, M) cv2.imshow("Subtracted", subtracted) cv2.waitKey(0)

Now save this file named Arithmetic .py and exit using ctrl + x, y, enter. we simply open up a raspberry terminal window and execute the following command:

python Arithmetic.py --image bay.jpg

see like this interface

**≡ Analysis**

from __future__ import print_function import numpy as np import argparse import cv2

In the tutorial, you’ll see importing the print_ function from the __future__ package. We’ll be using that because of the actual print() function rather than the print statement so that this code will work with both Python 2 and Python 3. use **argparse** to handle parsing our command-line arguments. Then, **cv2 is imported – cv2** is our OpenCV library and contains our image processing functions.

# Construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args())

This code handle parsing the command line arguments. The single argument we need is –image: the path to our image on disk. Lastly, we parse the arguments and store them in a dictionary.

# Load the image and show some basic information on it image = cv2.imread(args["image"])

Now that we have the path to the image, we can load it off the disk using the **cv2.imread** function. The **cv2.imread** function returns a NumPy array representing the image that you lode.

print("max of 255: {}".format(cv2.add(np.uint8([200]), np.uint8([100]))))

we set two NumPy arrays that are 8-bit unsigned integers The first array has one element a value of 200. The second array also has only one element, but with a value of 100. We then apply OpenCV’s `cv2.add` method to add the values together.

Well, according to usual arithmetic rules, we would think the result should be 300, but, remember that we are going with 8-bit unsigned integers that only have a range between [0, 255]. Since we are doing the `cv2.add` method, OpenCV takes care of clipping for us and ensures that the addition produces a maximum value of 255.

print("min of 0: {}".format(cv2.subtract(np.uint8([50]), np.uint8([100]))))

Tn This code then works subtraction working `cv2.subtract`. Again, we set two NumPy arrays, each with a single element, and of the 8-bit unsigned integer data type. The first array has a value of 50 and the second a value of 100.

According to our arithmetic rules, the subtraction should return a value of −50; but, OpenCV once again performs clipping for us. We find that the value is clipped to a value of 0.

print("wrap around: {}".format(np.uint8([200]) + np.uint8([100]))) print("wrap around: {}".format(np.uint8([50]) - np.uint8([100])))

In this section, we set two NumPy arrays, all with a single element, and of the 8-bit unsigned integer data type. The first array has a value of 200, and the second has a value of 100. Doing the `cv2.add` function, our addition would be clipped and a value of 255 returned.

But, NumPy does not show clipping – it instead performs modulo arithmetic and “wraps around”. Once a value of 255 is reached, NumPy wraps about to zero and then starts counting up again, until 100 steps have been reached.

Then, we set two more NumPy arrays, one has a value of 50 and the other 100. Applying the ** cv2.subtract** method, this subtraction would be clipped to return a value of 0. But, we know that NumPy performs modulo arithmetic rather than clipping. Instead, once 0 is reached during the subtraction, the modules operations wraps around and start counting backward from 255.

**wrap around: [44]****wrap around: [206]**

#### If giving integer arithmetic, it is important to keep in mind your desired output.

Do you need all values to be clipped if they fall outside the range [0, 255]? Then use OpenCV’s built-in methods for image arithmetic.

Do you need modulus arithmetic operations and have values wrap around if they fall outside the range of [0, 255]? Then only add and subtract the NumPy arrays as you usually would.

M = np.ones(image.shape, dtype = "uint8") * 100 added = cv2.add(image, M) cv2.imshow("Added", added) # Similarly, we can subtract 50 from all pixels in our # image and make it darker: M = np.ones(image.shape, dtype = "uint8") * 50 subtracted = cv2.subtract(image, M) cv2.imshow("Subtracted", subtracted) cv2.waitKey(0)

This section sets a NumPy array of ones, with the same size as our image. we are sure to use 8-bit unsigned integers as our data type. In order to fill our matrix with values of 100’s rather than 1’s, we only multiply our matrix of 1’s by 100. Finally, we apply the ** cv2.add** function to add our matrix of 100’s to the original image – thus increasing every pixel intensity in the image by 100, but assuring all values are clipped to the range [0, 255] if they attempt to exceed 255.

We then create another NumPy array filled with the ’50s and use the ** cv2.subtract** function to subtract 50 from each pixel intensity of the image. Our image now looks considerably darker than the original T-Rex. Pixels that were once white now look gray. This is because we are subtracting 50 from the pixels and pushing them towards the darker regions of the RGB color space.

In this section, we examined the peculiarities of image arithmetic using OpenCV raspberrypi and NumPy. These signs are important to keep in mind, unless, you may get unwanted results when performing arithmetic operations on your images.

More Computer vision tutorial on raspberry pi click COMPUTER VISION BEGINNER

Visit My Blog

633 total views, 1 views today