简体   繁体   中英

Applying original image pixels wherever the thresholded image is black in OpenCV/numpy?

I've applied some morphological operations on a thresholded image and now I want to convert it back to the original image, but only wherever the image is black. Here's some example pseudocode of what I'm trying to do:

import cv2
import numpy as np

img = cv2.imread("img01.jpg")
empty_image = np.zeros([img.width,img.height,3],dtype=np.uint8)
grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

ret,thresh1 = cv2.threshold(grey,125,255,cv2.THRESH_BINARY)
kernel = np.ones((5, 5), np.uint8) 
mask = cv2.erode(thresh1, kernel, iterations=2)
mask = cv2.dilate(mask, kernel, iterations=2)
for(i in mask):
      if(mask[i]>0]:
          empty_image[i]=img[i]

In other terms: How can I restore parts of an original image to parts of a thresholded image?

After find the mask just use result = cv2.bitwise_and(img,img,mask=mask) with no need to declare an empty image, which is called mask process.

Another way is to use boolean indexing as img[mask==0] = 0 to make every image pixel zero (black) if it's black in the mask.

And that is the result:

将蒙版应用于图像的结果

This link for useful example to understand bitwise_and and other simple related operations in opencv docs.

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