opencv-python中 boundingRect()函数解析

boundingRect()函数解释:矩形边框(Bounding Rectangle)是说,用一个最小的矩形,把找到的形状包起来。还有一个带旋转的矩形,面积会更小,效果见下图

 


def boundingRect(array): # real signature unknown; restored from __doc__
    """
    boundingRect(array) -> retval
    .   @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image.
    .   
    .   The function calculates and returns the minimal up-right bounding rectangle for the specified point set or
    .   non-zero pixels of gray-scale image.
    .   
    .   @param array Input gray-scale image or 2D point set, stored in std::vector or Mat.
    """
    pass
  • 输入:是一个轮廓点集合,也就是它的参数,可以通过cv2.findContours获取。
  • 返回四个值,分别是x,y,w,h;(x,y)是矩阵左上点的坐标,w,h分别是是矩阵的宽和高。目标中心,为:(x+w//2,y+h//2)
# 读取图像
bgr_img = cv2.imread("./img.jpg")
copy_img = bgr_img.copy()
# bgr图像转化为灰度图像
gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY)
# 灰度图像转化为二值图像
th, binary = cv2.threshold(gray_img, 0, 255, cv2.THRESH_OTSU)
# 轮廓函数返回值为两个,第一个是轮廓contours
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(copy_img, contours, -1, (0, 0, 255), 3)
 
bounding_boxes = [cv2.boundingRect(cnt) for cnt in contours]
 
for bbox in bounding_boxes:
    '''寻找x,y坐标以及宽度和高度'''
     [x , y, w, h] = bbox
     cv2.rectangle(bgr_img, (x, y), (x + w, y + h), (0, 255, 0), 2)
 
cv2.imshow("name", bgr_img)
cv2.waitKey(0)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值