Ask Your Question

How can I modify ROI and then add it to the original image using Python?

asked 2020-08-17 01:24:52 -0500

Muzaffar gravatar image

I am new to Python and OpenCV. My task is to perform some operations on the ROI of an image and then adding back that image to the original image. How could I achieve this? For example, I want to change the colour of the ROI image and then add it back. My code is given below:

for (i,c) in enumerate(contours_from_left_to_right):    
     cv2.drawContours(duplicate_img, [c], -1, (0,0,255), 3)
     cent_moment = cv2.moments(c)
     centroid_x = int(cent_moment['m10'] / cent_moment['m00'])
     centroid_y = int(cent_moment['m01'] / cent_moment['m00'])
     cv2.putText(duplicate_img, str(i+1), (centroid_x, centroid_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
     cv2.imshow('Contours from Left to Right', duplicate_img)
 (x, y, w, h) = cv2.boundingRect(c)    
 print("Top-Left Corner=",(x,y), "width= ",w,"height =",h)      
 ROI = roi_img[y:y+h, x:x+w]    
 cv2.imwrite("ROI_{}.png".format(image_number), ROI)
 image_number += 1
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2020-08-17 05:16:22 -0500

berak gravatar image

it's not even a real opencv problem --

ROI's are just numpy slices, if you modify them, you modify the original image data, no need to copy anything back, see:

>>> a = np.zeros((200,200,3),dtype=np.uint8)
>>> a[80:120,80:120,:] = (127,127,127)
>>> cv2.imshow("A",a)
>>> cv2.waitKey()

image description

edit flag offensive delete link more


p.s: @WenJuan 's answer on your SO question is plain BS ;)

berak gravatar imageberak ( 2020-08-17 08:21:04 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower


Asked: 2020-08-17 01:24:52 -0500

Seen: 58 times

Last updated: Aug 17