如何在 OpenCV Python 中找到图像轮廓的边界矩形?


物体的边界矩形是在图像中围绕物体绘制的矩形。在OpenCV中有两种方法可以找到边界矩形 -

直边界矩形

它是一个直线矩形,因为它不考虑物体的旋转。可以使用函数cv2.boundingRect()计算。其语法如下 -

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

这里,“cnt”是轮廓点的数组。它返回边界矩形的左上角坐标(xy)以及宽度和高度(wh)。

旋转矩形

它考虑了物体的旋转,并绘制一个面积最小的矩形。旋转矩形是使用函数cv2.minAreaRect()找到的。它返回左上角坐标(xy),(widthheight),旋转角度。矩形的4个角可以使用函数cv2.boxPoints()获得。

rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
img = cv2.drawContours(img,[box],0,(0,255,255),2)

步骤

您可以使用以下步骤来计算给定函数的雅可比矩阵 -

  • 导入所需的库。所需的库是OpenCVNumPy

  • 加载输入图像。将输入图像转换为灰度图像。

  • 对灰度图像应用阈值处理以创建二值图像。

  • 找到图像中物体的轮廓。

  • 使用上述轮廓计算直边界矩形。在图像上绘制矩形。

  • 计算旋转边界矩形并在图像上绘制它。

  • 显示带有绘制的直线和旋转边界矩形的图像。

我们将在以下示例中使用以下图像作为输入文件

示例 1

在下面的 Python 代码中,我们计算直边界矩形。

# import required libraries import cv2 # read the input image img = cv2.imread('approx.png') # convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding on the gray image to create a binary image ret,thresh = cv2.threshold(gray,127,255,0) # find the contours contours, _ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # take the first contour cnt = contours[0] # compute the bounding rectangle of the contour x,y,w,h = cv2.boundingRect(cnt) # draw contour img = cv2.drawContours(img,[cnt],0,(0,255,255),2) # draw the bounding rectangle img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) # display the image with bounding rectangle drawn on it cv2.imshow("Bounding Rectangle", img) cv2.waitKey(0) cv2.destroyAllWindows()

输出

执行上述代码时,它将生成以下输出窗口。

在上面的输出中,绿色矩形显示直边界矩形。

现在,让我们计算包含最小面积的旋转边界矩形。请参阅以下示例。

示例 2

在下面的 Python 代码中,我们计算直边界矩形和旋转边界矩形。比较输出窗口以清楚地了解两种边界矩形之间的区别。

import cv2 import numpy as np img = cv2.imread('approx.png') img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(img1,127,255,0) contours,_ = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # print("Number of contours detected:", len(contours)) cnt = contours[0] # compute straight bounding rectangle x,y,w,h = cv2.boundingRect(cnt) img = cv2.drawContours(img,[cnt],0,(255,255,0),2) img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) # compute rotated rectangle (minimum area) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) # draw minimum area rectangle (rotated rectangle) img = cv2.drawContours(img,[box],0,(0,255,255),2) cv2.imshow("Bounding Rectangles", img) cv2.waitKey(0) cv2.destroyAllWindows()

输出

执行上述代码时,它将生成以下输出窗口。

在上面的输出中,绿色矩形是直边界矩形,黄色矩形是最小面积的旋转矩形。注意这两个矩形之间的区别。

更新于: 2023年8月28日

27K+ 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.