I have a RGB image of 256X256 with the binary mask. I want to remove the object from the main image with the help of mask and keep the rest background.
I have tried with the below code but it didn't work.
Can anyone let me know where I made the mistake?
import cv2
import numpy as np
# read image
img = cv2.imread('image.jpg')
mask2 = cv2.imread('mask.jpg') / 1
# mask by multiplication, clip to range 0 to 255 and make integer
result2 = (img * mask2).clip(0, 255).astype(np.uint8)
# save results
cv2.imwrite('result.png', result1)
Image, Mask:
Output I want, The result I am getting:
CodePudding user response:
You need to use cv2.bitwise_and
for your problem. It performs 'AND' operation between your img
and mask
in a bitwise manner.
- For white region in the
mask
, correspondingimg
region is preserved - For white region in the
mask
, correspondingimg
region is occluded
Code:
img = cv2.imread(r'C:\Users\524316\Desktop\Stack\eye\eye.jpg')
mask = cv2.imread(r'C:\Users\524316\Desktop\Stack\eye\mask.jpg', 0)
# invert the mask
th = cv2.threshold(mask,0,255,cv2.THRESH_BINARY_INV cv2.THRESH_OTSU)[1]
# preserve the background
res = cv2.bitwise_and(img, img, mask = th)
Result:
CodePudding user response:
You don't need Otsu thresholding, just ordinary thresholding, with a sensible threshold. Your "mask" image is a JPEG. Lossy compression causes it to not be entirely black or white.
Once you have the mask, you just need to learn about masking operations. That is a feature of numpy
I'm using here:
im = cv.imread("VgAjK.jpg")
maskim = cv.imread("ZKKkp.jpg", cv.IMREAD_GRAYSCALE)
im[maskim >= 128] = 255 # "remove", paint over with white
You multiplied... that might have worked (except inverted) if your arrays had the right value ranges.