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:

  1. Incorrect File Name: The original code had a typo in the filename for the second image, 'opencv2.ipg' instead of 'opencv2.jpg'.

  2. Incorrect Image Addition: While the + operator can work in some scenarios, for image addition in OpenCV, it's best to use the dedicated cv2.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 the cv2.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!

OpenCV Image Addition: Correcting Errors and Improving Code

原文地址: https://www.cveoy.top/t/topic/bEzd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录