java中的接口是类吗
463
2022-11-01
圆形检测算法-基于颜色和形状(opencv)
import cv2import numpy as np# 圆检测算法def detect(img): # 定义红色、蓝色、白色的hsv区间文件 red1 = np.array([0, 100, 46]) red2 = np.array([8, 255, 255]) white1 = np.array([0, 0, 221]) white2 = np.array([180, 30, 255]) blue1 = np.array([100, 43, 46]) blue2 = np.array([124, 255, 255]) # 从rgb转到hsv颜色空间 hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # 找到每个像素的值,得到对应的单色图像 mask_red = cv2.inRange(hsv, red1, red2) mask_white = cv2.inRange(hsv, white1, white2) mask_blue = cv2.inRange(hsv, blue1, blue2) result_red = cv2.bitwise_and(img, img, mask=mask_red) result_white = cv2.bitwise_and(img, img, mask=mask_white) result_blue = cv2.bitwise_and(img, img, mask=mask_blue) # 对图像进行灰度化 gray_red = cv2.cvtColor(result_red, cv2.COLOR_BGR2GRAY) gray_white = cv2.cvtColor(result_white, cv2.COLOR_BGR2GRAY) gray_blue = cv2.cvtColor(result_blue, cv2.COLOR_BGR2GRAY) # 对灰度图像进行轮廓提取,更加面积,去除较大或较小面积,保存和圆相同的面积轮廓 _, contours, heridency = cv2.findContours(gray_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) _, contours2, heridency = cv2.findContours(gray_white, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 定义绘制字体 font = cv2.FONT_HERSHEY_SIMPLEX # 红色轮廓 for i in contours: # 计算轮廓面积 area = cv2.contourArea(i) # 当面积在500-2000之间,才进行圆检测 if 500 < area < 2000: circles_red = cv2.HoughCircles(gray_red, cv2.HOUGH_GRADIENT, 1, 50, param1=150, param2=20, minRadius=5, maxRadius=14) # 若不为空,则进行绘制 if circles_red is not None: circles_1 = np.uint16(np.around(circles_red)) for i in circles_1[0, :]: cv2.circle(img, (i[0], i[1]), i[2], (0, 0, 255), 2) # 画圆 cv2.circle(img, (i[0], i[1]), 2, (0, 0, 255), 2) # 画圆心 cv2.putText(img, 'red', (i[0], i[1]), font, 0.8, (0, 0, 255), 2) # 白色轮廓 for i in contours2: area = cv2.contourArea(i) if 350 < area < 1500: circles_white = cv2.HoughCircles(gray_white, cv2.HOUGH_GRADIENT, 1, 20, param1=35, param2=20, minRadius=0, maxRadius=30) if circles_white is not None: circles_2 = np.uint16(np.around(circles_white)) for i in circles_2[0, :]: cv2.circle(img, (i[0], i[1]), i[2], (255, 255, 255), 2) # 画圆 cv2.circle(img, (i[0], i[1]), 2, (255, 255, 255), 2) # 画圆心 cv2.putText(img, 'white', (i[0], i[1]), font, 0.8, (255, 255, 255), 2) # 因蓝色轮廓较少,所以不需要进行轮廓提取 circles_blue = cv2.HoughCircles(gray_blue, cv2.HOUGH_GRADIENT, 1, 50, param1=35, param2=20, minRadius=5, maxRadius=25) if circles_blue is not None: circles_3 = np.uint16(np.around(circles_blue)) for i in circles_3[0, :]: cv2.circle(img, (i[0], i[1]), i[2], (255, 0, 0), 2) # 画圆 cv2.circle(img, (i[0], i[1]), 2, (255, 0, 0), 2) # 画圆心 cv2.putText(img, 'blue', (i[0], i[1]), font, 0.8, (255, 0, 0), 2) return imgcap = cv2.VideoCapture('demo/DSC_0001.MOV')while(cap.isOpened()): ret, frame = cap.read() frame = cv2.resize(frame, (640, 480)) result = detect(frame) cv2.imshow('frame', result) if cv2.waitKey(25) & 0xFF == ord('q'): breakcap.release()cv2.destroyAllWindows()
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~