平时工作中图像处理经常会用到图像最大轮廓及最小外接矩形的获取:
计算过程如下:
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.blur(gray, (9, 9))
_, thresh = cv2.threshold(blurred, 155, 255, cv2.THRESH_BINARY)
_, cnts, _ = cv2.findContours( thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
rect = cv2.minAreaRect(c)
#box即为最小外接矩形坐标
box = np.int0(cv2.boxPoints(rect))
cv2.drawContours(img, [box], -1, (0, 255, 0), 3)
cv2.imshow("Image", img)
cv2.imwrite("pic.jpg", img)
cv2.waitKey(0)
然而有时候我们需要的是最大内接矩形,获取效果如下:
从轮廓中所有坐标中获取其中4个坐标即可:
获取过程如下:
def order_points(pts):
# pts为轮廓坐标
# 列表中存储元素分别为左上角,右上角,右下角和左下角
rect