简体   繁体   中英

Is it possible to paste an image on top of another in OpenCV?

I am fairly new to OpenCv and am creating a program that will segment a shoe from its background using GrabCut algorithm, then I want to paste the shoe onto a white background but I am struggling at that part.

I tried cv2.add() to add the two images together but the two images have to be the same size and I can't guarantee that since the program prompts the user to upload the image.

I have also tried whiteBgImg = 255 - grabCutImg to make the background white where the shoe isn't but it seems to affect the final image which is a problem as I need to perform feature detection and matching on the image.

Thank you in advance for the advice! :)

Original image: Original Shoe

Final image (after grabcut and whiteBgImg = 255 - grabCutImg applied): Grabcut Shoe

Here is one way to do that in Python/OpenCV.

Note that I invert your image to get back your original. Skip the invert if you start with your actual original before you inverted it.

  • Read the input and invert
  • Convert to gray
  • Threshold to make a mask
  • Create a white image the size of the input
  • Blend the two together with the shoe over the white using the mask to control which shows
  • Save the results

Input:

在此处输入图片说明

import cv2
import numpy as np

# load image
img = cv2.imread("shoe_inverted.jpg")

# invert the polarity
img = 255 - img

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold image and make 3 channels as mask
mask = cv2.threshold(gray, 32, 255, cv2.THRESH_BINARY)[1]
mask = cv2.merge([mask,mask,mask])

# create white image for background of result
white = np.full_like(img, (255,255,255))

# apply mask to img and white
result = np.where(mask!=0, img, white)

# write result to disk
cv2.imwrite("shoe_inverted_inverted.jpg", img)
cv2.imwrite("shoe_mask.jpg", mask)
cv2.imwrite("shoe_result.jpg", result)

cv2.imshow("IMAGE", img)
cv2.imshow("MASK", mask)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()


Inverted input to get back to your original:

在此处输入图片说明

Mask (after thresholding to clean the boundary):

在此处输入图片说明

Result:

在此处输入图片说明

If you want to put one image in front of the other image, you can do this as follows:

back_img[y_start:y_end,x_start:x_end] = front_img[y_start:y_end,x_start:x_end]

If you want to concat an image on the y axis, the images must be the same size. For this, you can look at cv2.resize or you can create a blank image with np.zeros to add padding to the image and "If you want to put one image in front of the other image" which I said in the first method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM