import cv2 import numpy as np import math def draw_mark_X(img, x, y, width=6, color=(0, 0, 255), penWid=1): cv2.line(img, (int(x - width), int(y - width)), (int(x + width), int(y + width)), color, penWid) cv2.line(img, (int(x - width), int(y + width)), (int(x + width), int(y - width)), color, penWid) # 设置HSV跟踪颜色范围 frame = cv2.imread('chengse.jpg') min_pipa_hsv = np.array([5,95,145]) max_pipa_hsv = np.array([25, 255, 255]) img_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #cv2.imshow('test', img_hsv) # 提取颜色范围内图像区域 PingPangMask = cv2.inRange(img_hsv, min_pipa_hsv, max_pipa_hsv) img_pipa = cv2.bitwise_and(frame, frame, mask=PingPangMask) #cv2.imshow('test', img_pipa) # 二值化 kernel = np.ones((6, 6), np.uint8) img_kai = cv2.morphologyEx(img_pipa, cv2.MORPH_OPEN, kernel) #cv2.imshow('test', img_kai) # 从开运算后的图像提取HSV终点亮度分度 img_kai_chv = img_kai[:, :, 2] #cv2.imshow('test', img_kai_chv) #二值化 阈值为63 小于63的变为0 大于63的变为255 thr, img_bin = cv2.threshold(img_kai_chv, 63, 255, cv2.THRESH_BINARY) #cv2.imshow('test', img_bin) # 提取轮廓 contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 画绿色轮廓线 cv2.drawContours(frame, contours, -1, (0, 255, 0), 1) #cv2.imshow('test', frame) # 画红色轮廓最小外接圆 (x, y), radius = cv2.minEnclosingCircle(contours[0]) center = (int(x), int(y)) radius = int(radius) cv2.circle(frame, center, radius, (0, 0, 255), 1) draw_mark_X(frame, int(x), int(y)) #cv2.imshow('test', frame) # 画白色最优拟合椭圆 ellipse = cv2.fitEllipse(contours[0]) # 最优拟合椭圆 cv2.ellipse(frame, ellipse, (255, 255, 255), 1) #cv2.imshow('test', frame) # 计算最小外接圆面积 area = math.pi * radius * radius # 显示圆心X Y 坐标,半径 R, 和 圆面积 font = cv2.FONT_HERSHEY_SIMPLEX text_info = 'X:' + str(x * 10 // 1 / 10) + ' Y:' + str(y * 10 // 1 / 10) cv2.putText(frame, text_info, (10, 30), font, 1, (0, 255, 0), 1) text_info = 'R:' + str(radius * 10 // 1 / 10) + " Area:" + str(area * 100 // 1 / 100) cv2.putText(frame, text_info, (10, 60), font, 1, (0, 255, 0), 1) #cv2.imshow('test', frame) cv2.waitKey(0) cv2.destroyAllWindows()
opencv实现小球轮廓检测,绘制外接圆,显示坐标信息。
最新推荐文章于 2024-05-11 17:25:51 发布