# -*- coding: utf-8 -*-
import cv2
import numpy as np
import imutils
def Detector_color(frame,x,y,r):
color_list = []
frame = frame[y-r-2:y+r+2,x-r-2:x+r+2]
cv2.imwrite('J03-3' + '.png', frame)
frame = imutils.resize(frame, width=600)
blurred = cv2.GaussianBlur(frame, (7, 7), 0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
edged = cv2.inRange(hsv, (0, 0, 0), (180, 255, 255))
edged = cv2.dilate(edged, None, iterations=2)
edged = cv2.erode(edged, None, iterations=2)
mask1 = cv2.inRange(hsv, (36, 43, 46), (77, 255, 255))# 绿色
mask2 = cv2.inRange(hsv, (100, 43, 46), (124, 255, 255))#蓝色
mask3 = cv2.inRange(hsv, (156, 43, 46), (165, 255, 255)) #红色
mask4 = cv2.inRange(hsv, (166, 43, 46), (180, 255, 255))# 橙色
mask5 = cv2.inRange(hsv, (26, 43, 46), (34, 255, 255))#黄色
mask6 = cv2.inRange(hsv, (78, 43, 46), (99, 255, 255))# 青色
mask7 = cv2.inRange(hsv, (125, 43, 46), (155, 255, 255))# 紫色
mask = {"green": mask1, "blue": mask2, "red": mask3,"orange": mask4, "yellow": mask5, "cyan": mask6,"purple": mask7}
for key, value in mask.items():
target = cv2.bitwise_and(edged, edged, mask=value)
cnts = cv2.findContours(target, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
for c in cnts:
if cv2.contourArea(c) < 12000:
continue
else:
color_list.append(key)
return color_list
capture = cv2.VideoCapture('ball.mp4') # 打开摄像头
while True:
ret, frame = capture.read() # 返回值,每一帧图像
if ret==False:
break
dst = cv2.medianBlur(frame, 5) # 中值滤波
cv2.imshow("median video", dst)
hsv = cv2.cvtColor(dst, cv2.COLOR_BGR2HSV)
cv2.imshow("hsv", hsv)
lower_hsv = np.array([0, 0, 221])
upper_hsv = np.array([180, 30, 255])
extract_white = cv2.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)
cv2.imshow("extract_red demo", extract_white)
canny = cv2.Canny(dst, 40, 80)
cv2.imshow('canny video', canny)
circles = cv2.HoughCircles(canny, cv2.HOUGH_GRADIENT, 1, 50, param1=80, param2=30, minRadius=60, maxRadius=150)
# 输出检测到圆的个数
#print("Sum:%d" % len(circles[0]))
try:
# 根据检测到圆的信息,画出每一个圆
for circle in circles[0]:
x = int(circle[0])
y = int(circle[1])
r = int(circle[2])
if len(circles[0])==3 or len(circles[0])==4:
color = Detector_color(frame,x,y,r)
img = cv2.rectangle(frame,(x-r,y-r),(x+r,y+r),color=(30,130,75),thickness=3)
cv2.putText(frame, color[0], (x-r, y-r-10), cv2.FONT_HERSHEY_DUPLEX, 1,(0, 0, 255), 1)
else:
img = cv2.circle(frame, (x, y), r, (0, 0, 255), 1, 8, 0)
except:
pass
cv2.imshow("video", img)
print('---'*10)
key = cv2.waitKey(400)
if key == 27: # Esc退出
break
cv2.destroyAllWindows()
- 1
- 2
- 3
前往页