opencv实现小球轮廓检测,绘制外接圆,显示坐标信息。

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()
  • 15
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值