简体   繁体   中英

How to define boundaries for HSV color in OpenCV

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)

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]

在此处输入图像描述

在此处输入图像描述

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