Reputation: 80
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?
Upvotes: 0
Views: 430
Reputation: 334
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.
Upvotes: 1