python 拟合圆心_OpenCV:将单个圆拟合到图像(在Python中)

该博客介绍了如何使用Python和OpenCV库来检测图像中的圆形对象。首先,通过阈值处理和形态学操作获取二值图像,然后找到最大的轮廓并计算其最小外接圆和最佳拟合椭圆。最终,使用cv2.minEnclosingCircle和cv2.fitEllipse函数在图像上绘制了圆心和椭圆边界。
摘要由CSDN通过智能技术生成

如果对象是圆形的,那么使用cv2.minEnclosingCircle是很好的。或者,您可以使用cv2.fitEllipse来找到对象周围最合适的椭圆。记住一定要在黑色背景下找到白色物体的轮廓。在import cv2

import numpy as np

img = cv2.imread("1.jpg")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

_,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

thresh = cv2.bitwise_not(thresh)

element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(5, 5))

morph_img = thresh.copy()

cv2.morphologyEx(src=thresh, op=cv2.MORPH_CLOSE, kernel=element, dst=morph_img)

contours,_ = cv2.findContours(morph_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

areas = [cv2.contourArea(c) for c in contours]

sorted_areas = np.sort(areas)

#bounding box (red)

cnt=contours[areas.index(sorted_areas[-1])] #the biggest contour

r = cv2.boundingRect(cnt)

cv2.rectangle(img,(r[0],r[1]),(r[0]+r[2],r[1]+r[3]),(0,0,255),2)

#min circle (green)

(x,y),radius = cv2.minEnclosingCircle(cnt)

center = (int(x),int(y))

radius = int(radius)

cv2.circle(img,center,radius,(0,255,0),2)

#fit ellipse (blue)

ellipse = cv2.fitEllipse(cnt)

cv2.ellipse(img,ellipse,(255,0,0),2)

cv2.imshow("morph_img",morph_img)

cv2.imshow("img", img)

cv2.waitKey()

aMZsH.pngvhuAp.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值