OpenCV Image Addition: Correcting Errors and Improving Code
OpenCV Image Addition: Correcting Errors and Improving Code
This code demonstrates how to add two images using OpenCV in Python. We'll go through some common errors and how to fix them, resulting in a clean and efficient code for image manipulation.
Original Code (with Errors):
import cv2
img1 = cv2.imread('1.jpg',cv2.IMREAD_REDUCED_COLOR_2)
img2 = cv2.imread('opencv2.ipg',cv2.IMREAD_REDUCED_COLOR_2)
img3 =img1+img2
img4 = cv2.add(img1,img2)
cv2.imshow('1',img1)
cv2.imshow('2',img2)
cv2.imshow('1+2',img3)
cv2.imshow('1add2',img4)
cv2.waitKey(0)
Corrected Code:
import cv2
img1 = cv2.imread('1.jpg', cv2.IMREAD_REDUCED_COLOR_2)
img2 = cv2.imread('opencv2.jpg', cv2.IMREAD_REDUCED_COLOR_2)
img3 = cv2.add(img1, img2)
cv2.imshow('1', img1)
cv2.imshow('2', img2)
cv2.imshow('1+2', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation of Errors:
-
Incorrect File Name: The original code had a typo in the filename for the second image, 'opencv2.ipg' instead of 'opencv2.jpg'.
-
Incorrect Image Addition: While the
+operator can work in some scenarios, for image addition in OpenCV, it's best to use the dedicatedcv2.add()function. This ensures proper handling of pixel values and overflow prevention.
Further Improvement:
- We've added
cv2.destroyAllWindows()at the end of the code to close all open windows after thecv2.waitKey(0)function. This provides a cleaner way to end the program.
By correcting these errors and using the cv2.add() function, you'll get accurate image addition and avoid unexpected results. Happy image processing!
原文地址: https://www.cveoy.top/t/topic/bEzd 著作权归作者所有。请勿转载和采集!