求边界矩形
直接上代码:
import cv2
import numpy as np
# 读取图像,如有必要转化成黑白图像
img = cv2.imread("water.jpg", cv2.IMREAD_UNCHANGED)
# 二值化
ret, thresh = cv2.threshold(img.copy(), 15, 255, cv2.THRESH_BINARY)
# 寻找边界
image, contours, hier = cv2.findContours(thresh,
cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 根据边界获取边界矩形,返回值是元组
for c in contours: # shape:(1, 812, 1, 2)
x, y, w, h = cv2.boundingRect(c) # shape:(812, 1, 2)
cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)
#cv2.drawContours(img, contours, -1, 255, 1)
cv2.imwrite("contours.png", img)
cv2.imshow("contours", img)
cv2.waitKey()
cv2.destroyAllWindows()