1

I was trying to perform image segmentation using color space. For example, rustic region. I wasn't sure how to select the boundaries for cv2.inRange().

img = cv2.imread(file)
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_bound = np.array([0,70,70])
upper_bound = np.array([20,200,150])
mask0 = cv2.inRange(img_hsv, lower_bound, upper_bound)

lower_bound = np.array([170,70,70])
upper_bound = np.array([180,200,150])
mask1 = cv2.inRange(img_hsv, lower_bound, upper_bound)

# add both masks
mask = mask0+mask1

output_img = cv2.bitwise_and(img,img,mask=mask)
Eden
  • 13
  • 4

1 Answers1

1

If you are trying to segment only the rusty part and not the other ones i tried some code as follow.

import cv2
import numpy as np

img = cv2.imread("rust1.png",1)
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_bound = np.array([120, 80, 0],dtype="uint8")
upper_bound = np.array([255, 255, 80],dtype="uint8")
mask0 = cv2.inRange(img_hsv, lower_bound, upper_bound)
cv2.imshow("mask",mask0)
output_img1 = cv2.bitwise_and(img,img,mask=mask0)

lower_bound = np.array([100,50,50])
upper_bound = np.array([205,205,88])
mask1 = cv2.inRange(img_hsv, lower_bound, upper_bound)
output_img2 = cv2.bitwise_and(img,img,mask=mask1)
cv2.imshow("mask1",mask1)

final = cv2.bitwise_or(output_img1, output_img2)

cv2.imshow("rust",np.hstack([img,final]))[![enter image description here][1]][1]

enter image description here

enter image description here

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • Great! May I know how you chose the boundaries? e.g. [120, 80, 0], [255, 255, 80] – Eden Sep 27 '21 at 06:27
  • @Eden Just play with those HSV range.Normal HSV range:H = 0-360, S = 0-100 and V = 0-100. Opencv HSV range: H: 0-179, S: 0-255, V: 0-255.Different applications use different scales for HSV. Refer similar problem[link](https://stackoverflow.com/questions/10948589/choosing-the-correct-upper-and-lower-hsv-boundaries-for-color-detection-withcv) – Nishani Kasineshan Sep 27 '21 at 07:07
  • Thank you so much – Eden Sep 27 '21 at 16:07