opencv_identification

我使用的是颜色分割法检测网球

在光线恒定的环境之下检测效果稳定

效果:

image-20220826125250181

image-20220826125315427

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import cv2
import numpy as np
low_h = np.array([93, 100, 90]) #设置象棋hsv的上下阈值
high_h = np.array([104, 160, 130])
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) #设定高斯滤波的卷积核
img = cv2.imread('xiangqi1.jpg')
Hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) #将jpg格式的图片通过颜色空间转换为HSV
ghsv = cv2.GaussianBlur(Hsv,(3,3),0) #高斯模糊
mask = cv2.inRange(ghsv,low_h,high_h) #通过inRange()函数将low之下high以上的颜色擦除
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) #闭运算和开运算除去象棋以外的噪点
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #findcontours查找角点
for c in contours:
x, y,w,h = cv2.boundingRect(c) #得到角点的左上角坐标和矩形的长宽
if(w*h>10000):
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2) #画图
cv2.imshow('img',img)
#cv2.imshow('mask',mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

视频流操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import cv2
import numpy as np
cat = cv2.VideoCapture(0)
low_h = np.array([93, 100, 90])
high_h = np.array([103, 160, 130])
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
def corner(img):
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
ghsv = cv2.GaussianBlur(hsv, (3, 3), 0)
mask = cv2.inRange(ghsv, low_h, high_h)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) #开运算
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) #闭运算
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return contours
def draw(contours, img):
for c in contours:
x, y, w, h = cv2.boundingRect(c)
if cv2.contourArea(c) > 400:
print('x:',x,'y:',y)
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
else:
continue
return img
while True:
ret, frame = cat.read()
if not ret:
break
contours = corner(frame)
img = draw(contours, frame)
cv2.imshow('img', img)
if cv2.waitKey(10) == ord('q'):
break
cv2.destroyAllWindows()

待测物体的HSV阈值不同光线下会不一样,不同环境需要用不同的值