python
复制代码
import cv2
import numpy as np
# 1输入图片
img=cv2.imread('./8.png')
img=cv2.resize(img,(0,0),fx=0.7,fy=0.7)
# 2识别颜色,转换HSV颜色空间
img_hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
# 3设定要识别的颜色范围,并利用inrange找到该范围
hsv_min=np.array([26,43,46])
hsv_max=np.array([34,255,255])
img_mask=cv2.inRange(img_hsv,hsv_min,hsv_max)
# 4进行滤波
img_median_blur=cv2.medianBlur(img_mask,3)
# 5 进行形态学变换,先腐蚀再膨胀
kernal=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
img_e=cv2.erode(img_median_blur,kernal)
img_d=cv2.dilate(img_e,kernal)
# 6 寻找轮廓
contours,hierarchy=cv2.findContours(
img_d,
cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE
)
# 7 for循环寻找轮廓,通过面积筛选出你想要的轮廓,绘制轮廓
img_copy = img.copy()
for i in contours:
if 200<cv2.contourArea(i)<2000000:
cv2.drawContours(img_copy,
[i],
0,
(0, 0, 255),
2
)
else:
continue
# 8 输出图片
cv2.imshow('img',img_copy)
cv2.waitKey(0)