1. 阈值调整,交互式的阈值调整,确定上限和下限:
import cv2 as cv
import numpy as np
def Tcallback(event):
H = cv.getTrackbarPos('H', 'show_pic')
S = cv.getTrackbarPos('S', 'show_pic')
V = cv.getTrackbarPos('V', 'show_pic')
H0 = cv.getTrackbarPos('H0', 'show_pic')
S0 = cv.getTrackbarPos('S0', 'show_pic')
V0 = cv.getTrackbarPos('V0', 'show_pic')
lower_red = np.array([H0, S0, V0])
upper_red = np.array([H, S, V])
mask = cv.inRange(hsv, lower_red, upper_red)
res = cv.bitwise_and(img, img, mask=mask)
cv.imshow('show_pic', res)
img = cv.imread('sam2.png')#, 1)
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV_FULL)
cv.namedWindow('show_pic')
cv.resizeWindow('show_pic', 640, 480)
cv.createTrackbar('H', 'show_pic', 255, 255, Tcallback)
cv.createTrackbar('S', 'show_pic', 255, 255, Tcallback)
cv.createTrackbar('V', 'show_pic', 255, 255, Tcallback)
cv.createTrackbar('H0', 'show_pic', 0, 255, Tcallback)
cv.createTrackbar('S0', 'show_pic', 43, 255, Tcallback)
cv.createTrackbar('V0', 'show_pic', 46, 255, Tcallback)
if cv.waitKey(0) == ord('q'):
cv.destroyAllWindows()
2. 阈值分割,并找到最大轮廓
现根据mask找到所有轮廓
对所有轮廓排序,找到最大的文章来源:https://www.toymoban.com/news/detail-665264.html
再对最大轮廓去凸多边形,用来对噪声做过滤。文章来源地址https://www.toymoban.com/news/detail-665264.html
img=cv2.resize(img,(640,480))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV_FULL)
mask_green=cv2.inRange(hsv, self.lower_green, self.upper_green)
img_c,contours, hierarchy = cv2.findContours(mask_green,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
list_c=sorted(contours,key=cv2.contourArea,reverse=True)
c_max=list_c[0]
approx = cv2.approxPolyDP(c_max, 0.01 * cv2.arcLength(c_max, True), True)
hull = cv2.convexHull(c_max)
到了这里,关于基于颜色进行轮廓分割,基于opencv和python的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!