最小矩形包围框,使用 OpenCV 库的 Python 代码

最小矩形包围框,使用 OpenCV 库的 Python 代码

import cv2
import numpy as np

def minAreaRect(contour):
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
return box

img = cv2.imread("input.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for contour in contours:
box = minAreaRect(contour)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)

cv2.imshow("result", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

以上代码首先加载了一张名为 input.png 的图像,然后对图像进行了灰度化和二值化处理,最后找到了图像中的轮廓,并绘制了最小矩形包围框。