I'm trying to crop an image based on the mask image and paste the cropped image on the new background image. I was able to achieve this but the cropped image is in gray color instead of color as in the original image
As it can be seen in the above image cropped image color is not the same as the original source cat image color, cropped image is a greyish color whereas in the original image it contains yellow golden color.
my code is as below to perform this
import cv2
src1=cv2.imread('cat.jpg',0)
mask=cv2.imread('mask_cat.jpg',0)
ret, thresh1 = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
src1 [thresh1==0] = 0
h, w = src1.shape
red = (0, 0, 0)
width, height = 1742, 815
back =cv2.cvtColor( create_blank(width, height, rgb_color=red),cv2.COLOR_BGR2GRAY)
hh, ww = back.shape
yoff = round((hh-h)/2)
xoff = round((ww-w)/2)
result = back.copy()
result[yoff:yoff h, xoff:xoff w] = src1
How can I get the same color in the cropped image as the original source color from where it cropped? Any suggestion or help solving this will be appreciated.
CodePudding user response:
import cv2
cat = cv2.imread('cat.jpg')
mask_cat = cv2.imread('mask_cat.jpg', 0)
result = cv2.bitwise_and(cat,cat,mask = mask_cat)
I also see you try to reshape the image.It can be done as follows.
width, height = 1742, 815
reshaped_result = cv2.resize(result, dsize=(width, height))
To place the cropped image on resized image
width, height = 1742, 815
result_final = np.zeros((height,width,3), np.uint8)
h, w = result.shape[:2]
hh, ww = result_final.shape[:2]
yoff = round((hh-h)/2)
xoff = round((ww-w)/2)
result_final[yoff:yoff h, xoff:xoff w] = result