python cv.rectangle_Python-OpenCV学习(七)边界框、最小矩形区域和最小闭圆的轮廓:...

边界框、最小矩形区域和最小闭圆的轮廓:

找到一个正方形轮廓很简单 找不规则的、歪斜的以及旋转的形状可用OpencV的cv2.findContours函数。

import cv2

import numpy as np

img = cv2.pyrDown(cv2.imread("hammer.jpg", cv2.IMREAD_UNCHANGED))

ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) , 127, 255, cv2.THRESH_BINARY)

image, contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for c in contours:

# find bounding box coordinates

x,y,w,h = cv2.boundingRect(c)

cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)

# find minimum area

rect = cv2.minAreaRect(c)

# calculate coordinates of the minimum area rectangle

box = cv2.boxPoints(rect)

# normalize coordinates to integers

box = np.int0(box)

# draw contours

cv2.drawContours(img, [box], 0, (0,0, 255), 3)

# calculate center and radius of minimum enclosing circle

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

# cast to integers

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

radius = int(radius)

# draw the circle

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

cv2.drawContours(img, contours, -1, (255, 0, 0), 1)

cv2.imshow("contours", img)

cv2.waitKey()

cv2.destroyAllWindows()

结果:

加载图片后先进行阈值处理,由于原图为黑白图片所以阈值较为简单

计算简单的边界框:

x,y,w,h=cv2.boundingRect(c)

转化为框的坐标及宽度,再画出框:

cv.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

第二步计算出包围最小的矩形区域

rect = cv2.minAreaRect(c)

# calculate coordinates of the minimum area rectangle

box = cv2.boxPoints(rect)

# normalize coordinates to integers

box = np.int0(box)

注意计算所得的顶点坐标为浮点型的,像素坐标必须为整数,所以必须做一个转换,然后画出这个矩形,可以用cv2.drawContours函数来:

cv2.drawContours(img,[box],0,(0,0,255),3)

该函数的第二个参数接收一个保存着轮廓的数组,从而可以在一次操作中绘制一系列轮廓。第三个参数为所要绘制的轮廓的索引,-1为绘制所有的轮廓,否则只会绘制轮廓组中指定的轮廓

最后检查的边界轮廓为最小闭圆:

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

# cast to integers

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

radius = int(radius)

cv2.minEnclosingCircle函数会返回一个二元组,第一个元素为圆心坐标组成的元组,第二个元素为圆的半径值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值