[英]How to mask out the object from the image?
我有一個帶有二進制掩碼的 256X256 的 RGB 圖像。 我想借助掩碼從主圖像中刪除 object 並保留 rest 背景。
我已經嘗試過使用下面的代碼,但它沒有用。
誰能讓我知道我在哪里犯了錯誤?
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)
圖片,面具:
Output 我想要,我得到的結果:
您需要使用cv2.bitwise_and
來解決您的問題。 它以按位方式在您的img
和mask
之間執行“與”操作。
mask
中的白色區域,保留對應的img
區域mask
中的白色區域,對應的img
區域被遮擋代碼:
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)
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.