In this Python OpenCV lesson we are going to learn about Python OpenCV Arithmetic Operations, there are two ways that you can do these Operations like Addition, Subtraction, Multiplication on images in Opencv. the first way is manually that you can add or Subtract two images manually, but in this way the result will not be good, the second way is the built in methods for opencv that you can use.
This is the complete code for the first way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import cv2 img1 = cv2.imread("lena_color_512.tif") img2 = cv2.imread("woman.tif") add = img1 + img2 print(add) subtract = img1 - img2 print(subtract) cv2.imshow("Addition", add) cv2.imshow("Subtract", subtract) cv2.waitKey(0) cv2.destroyAllWindows() |
You can see that we have manually added and subtracted the two images.
1 2 |
add = img1 + img2 subtract = img1 - img2 |
If you run the code you can see the we are receiving very poor result.
OK now let’s just use the built in methods in OpenCV for arithmetic operations, for adding we have add() method and for subtracting we have subtract() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import cv2 img1 = cv2.imread("lena_color_512.tif") img2 = cv2.imread("woman.tif") add2 = cv2.add(img1, img2) subtract2 = cv2.subtract(img1, img2) cv2.imshow("Add 2", add2) cv2.imshow("Sub 2", subtract2) cv2.waitKey(0) cv2.destroyAllWindows() |
Run the code and this time we are receiving better result.