Reputation: 45
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
Upvotes: 1
Views: 3031
Reputation: 53182
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.
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:
Upvotes: 2
Reputation: 128
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.
Upvotes: 0