获取所有轮廓的外接矩形
示例代码
python
import cv2
def get_contours_rectangle(mask):
h, w = mask.shape
contours, _ = cv2.findContours(
mask,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE
)
# 获取所有轮廓的外接矩形
min_y, max_y = h, 0
min_x, max_x = w, 0
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
min_y = min(min_y, y)
min_x = min(min_x, x)
max_y = max(max_y, y + h)
max_x = max(max_x, x + w)
w = max_x - min_x
h = max_y - min_y
mask_contour_rectangle = mask[min_y:max_y, min_x:max_x]
return mask_contour_rectangle
if __name__ == '__main__':
mask_path = "./test.png"
mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
mask_1 = get_contours_rectangle(mask)
cv2.imwrite("mask_contour.png", mask_1)