Copy cut out of an image to a new image using Numpy or OpenCV

Viewed 673

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 of an image. (both are the same size)

enter image description here enter image description here

Is it possible to copy the boat only where the pixels of the mask overlap to a specific part of a new image?

enter image description here

Here is the code I tried.

image1 = cv2.imread("boat.png")
mask = cv2.imread("boat_mask.png")
image2 = cv2.imread("sea.png")
width, height = image1.shape
image2[y:y+height,x:x+width] = image1[mask==255]

This doesn't work because image1[mask==255] no longer has a 2d shape.

Solution:

image2_cutout = image2[y:y+height,x:x+width]
image2_cutout[mask==255] = image1[mask==255]
image2[y:y+height,x:x+width] = image2_cutout
1 Answers

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.

Related