Skip to content Skip to sidebar Skip to footer

Copy Cut Out Of An Image To A New Image Using Numpy Or Opencv

Is it possible to copy only a specific region from an image and paste it to another image using either OpenCV or Numpy in python? Lets say I have a RGB image and a grayscale mask o

Solution 1:

Here it is:

import cv2


image1 = cv2.imread("data/boat.png")
_, mask = cv2.threshold(cv2.cvtColor(cv2.imread("data/masked_boat.png"), cv2.COLOR_BGR2GRAY), 120, 255, cv2.THRESH_BINARY)
image2 = cv2.imread("data/sea.jpg")
width, height, _ = image1.shape
y = 300
x = 300

masked_normalized = cv2.bitwise_and(image1, image1, mask=mask)

cut_from_bg = image2[x:x+width, y:y+height]
img1_bg = cv2.bitwise_and(cut_from_bg, cut_from_bg, mask=cv2.bitwise_not(mask))

dst = cv2.add(img1_bg, masked_normalized)

image2[x:width + x, y:height + y] = dst
cv2.imshow("sea_with_boat", image2)

cv2.waitKey(0)
cv2.destroyAllWindows()

The first thing that I do here is that I take a mask of boat and using cv2.bitwise_and I get a real masked image of boat. Then I cut a part of sea where I want to place the boat and cut out here the boat shape. Then I combine masked boat image and cutted sea image using cv2.add and after that I just put this part of image on the original image of sea.

Post a Comment for "Copy Cut Out Of An Image To A New Image Using Numpy Or Opencv"