python+opencv识别四种颜色,框定并标注

python+opencv识别四种颜色,框定并标注import cv2 as cv import numpy as np 读取视频 capture cv VideoCapture 0 height capture get cv CAP PROP FRAME HEIGHT width capture get cv CAP PROP FRAME WIDTH count

大家好,我是讯享网,很高兴认识大家。
import cv2 as cv import numpy as np # 读取视频 capture = cv.VideoCapture(0) height = capture.get(cv.CAP_PROP_FRAME_HEIGHT) width = capture.get(cv.CAP_PROP_FRAME_WIDTH) count = capture.get(cv.CAP_PROP_FRAME_COUNT) fps = capture.get(cv.CAP_PROP_FPS) print(height, width, count, fps) ball_color = ['green','red','blue'] def process(image, opt=1): # RGB转HSV色彩空间 hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV) # 结构元素 line = cv.getStructuringElement(cv.MORPH_RECT, (15, 15), (-1, -1)) # HSV范围 mask_red = cv.inRange(hsv, (0,60,60), (50,255,255)) mask_blue = cv.inRange(hsv, (100, 80, 46), (124,255,255)) mask_green = cv.inRange(hsv, (35,43,35), (90,255,255)) mask_yellow = cv.inRange(hsv,(11,34,43),(46,255,255)) # 开操作 masks = [mask_red,mask_blue,mask_green,mask_yellow] # 轮廓提取, 发现最大轮廓 i = 1 for mask in masks: contours, hierarchy = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) index = -1 max = 0 for c in range(len(contours)): area = cv.contourArea(contours[c]) if area > max: max = area index = c # 绘制 if index >= 0: rect = cv.minAreaRect(contours[index]) # 椭圆拟合 cv.ellipse(image, rect, (255, 0, 0), 2, 8) # 中心点定位 cv.circle(image, (np.int32(rect[0][0]), np.int32(rect[0][1])), 2, (0, 255, 0), 2, 8, 0) if i == 1: text = 'red' elif i == 2: text = 'blue' elif i == 3: text = 'green' elif i == 4: text = 'yellow' cv.putText(frame,text,(np.int32(rect[0][0]), np.int32(rect[0][1]) ), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2) i += 1 return image # 循环处理每一帧 while(True): ret, frame = capture.read() if ret is True: cv.imshow("video-input", frame) result = process(frame) cv.imshow("result", result) c = cv.waitKey(50) print(c) if c == 27: #ESC break else: break cv.waitKey(0) cv.destroyAllWindows()

讯享网


讯享网

小讯
上一篇 2025-03-26 18:13
下一篇 2025-02-14 09:28

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/47514.html