http://blog.csdn.net/dgut_guangdian/article/details/78535646
我上一篇写的跟踪很容易误判有很大随机性,而且不太准确现在做了一个改良版本:
import numpy as np
import math
import cv2
import time
def nothing(x):
pass
cap = cv2.VideoCapture(0) #打开摄像头0
var = cv2.CAP_PVAPI
LowerRed = np.array([24, 75, 37])
# 创建改变颜色的滚动条
cv2.namedWindow("fps") #新建一个窗口
cv2.createTrackbar('R','fps',89,255,nothing) #想要追踪颜色的R值
cv2.createTrackbar('G','fps',254,255,nothing) #想要追踪颜色的G值
cv2.createTrackbar('B','fps',254,255,nothing) #想要追踪颜色的B值
cv2.createTrackbar('threshold','fps',19,255,nothing) #二值化阈值
while(1):
#滑动条赋值
r = cv2.getTrackbarPos('R', 'fps')
g = cv2.getTrackbarPos('G', 'fps')
b = cv2.getTrackbarPos('B', 'fps')
c = cv2.getTrackbarPos('threshold', 'fps')
UpperRed = np.array([r, g, b])
ret, frame = cap.read()#得到每一帧
ret, frame1 = cap.read() # 得到每一帧
#hsv
HSV= cv2.cvtColor(frame, cv2.COLOR_RGB2HSV)
cv2.imshow("hsv",HSV)
#遮罩
mask = cv2.inRange(HSV, LowerRed, UpperRed)
kerne4=(11,11)
mask = cv2.morphologyEx(mask,cv2.MORPH_OPEN,kerne4)#闭运算让噪点更少
cv2.imshow("mask",mask)
RED_Things = cv2.bitwise_and(frame, frame, mask=mask)
cv2.imshow("red", RED_Things)
img_gray = cv2.cvtColor(RED_Things, cv2.COLOR_BGR2GRAY) # 灰度化
ret, img_threshold = cv2.threshold(img_gray, c, 255, cv2.THRESH_BINARY) # 二值化
# 膨胀+腐蚀等形态学变化
kerne1 = np.ones((3, 3), np.uint8)
img_erosin = cv2.erode(img_threshold, kerne1, iterations=1)
#cv2.imshow("dil",img_erosin)
kerne2 = np.ones((45, 45), np.uint8)
img_dilation = cv2.dilate(img_erosin, kerne2, iterations=1)
kerne3 = np.ones((11, 11), np.uint8)
img_dilation1 = cv2.dilate(img_dilation,kerne3,iterations=1)
#cv2.imshow("ers",img_dilation1)
kerne3 = np.ones((51, 51), np.uint8)
img_erosin1 = cv2.erode(img_dilation1, kerne3, iterations=1)
#图像相与
img_bit = cv2.bitwise_and(frame, frame, mask=img_erosin1)
cv2.imshow("bit",img_bit)
# 边缘caany
img_gray1 = cv2.cvtColor(img_bit, cv2.COLOR_BGR2GRAY) # 灰度化
ret, img_threshold1 = cv2.threshold(img_gray1, c, 255, cv2.THRESH_BINARY) # 二值化
canny = cv2.Canny(img_threshold1, 10, 200) # apertureSize默认为3
#cv2.imshow("img1",img_threshold1)
coutours = cv2.findContours(img_threshold1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]#得到轮廓
#由于可能遇到画面中没有绿色的场景避免程序意外中断所以把计算写入了try里面
if len(coutours) > 0:
c = max(coutours, key=cv2.contourArea)
M = cv2.moments(c) #计算中心
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
#得到中心然后在画面上显示
cv2.circle(frame1, (cx, cy), 9, (255, 0, 255), -1)
cv2.line(frame1,(cx,0),(cx,700),(255,0,0),3)
cv2.line(frame1,(0,cy),(700,cy),(255,0,0),3)
cv2.imshow("fps", frame1)
if cv2.waitKey(1) & 0xFF == ord('q'): #按q保存一张图片
cv2.imwrite("E:\cpy\pictures\\pic.jpg", frame1)
break
cap.release()
cv2.destroyAllWindows()
喜欢的点个赞把~