Home > Net >  How to extract the stain from the image?
How to extract the stain from the image?

Time:04-07

I have an image that has a stain (the green stain on the surface of the water), and my goal is to extract that stain. It was guiding me with enter image description here

The attempt:

img = cv2.imread('/content/001.jpg')

# blur
blur = cv2.GaussianBlur(img, (3,3), 0)

# convert to hsv and get saturation channel
sat = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)[:,:,1]

# threshold saturation channel
thresh = cv2.threshold(sat, 90, 255, cv2.THRESH_BINARY)[1]

# apply morphology close and open to make mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)
mask = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel, iterations=1)

# do OTSU threshold to get circuit image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)[1]

# write black to otsu image where mask is black
otsu_result = otsu.copy()
otsu_result[mask==0] = 0

# write black to input image where mask is black
img_result = img.copy()
img_result[mask==0] = 0

The result: enter image description here

CodePudding user response:

I followed your approach but used the LAB color space instead.

img = cv2.imread(image_path)

# blur
blur = cv2.GaussianBlur(img, (3,3), 0)

# convert to LAB space and get a-channel
lab = cv2.cvtColor(blur, cv2.COLOR_BGR2LAB)
a = lab[:,:,1]

thresh = cv2.threshold(a, 95, 255, cv2.THRESH_BINARY_INV)[1]
thresh = cv2.threshold(lab[:,:,1], 95, 255, cv2.THRESH_BINARY)[1]

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel, iterations=1)

inv_morph = cv2.bitwise_not(morph)
img_result = img.copy()
img_result[inv_morph==0] = 0
cv2.imshow('Final result', img_result)

enter image description here

The result is not accurate. You can alter the threshold value and/or morphological kernel to get the desired result.

  • Related