Python opencv 找包含多个区域的最小外接矩形

import cv2
import numpy as np
import copy

'''
包含多个区域的最小外接矩形'''
image = cv2.imread('./label.png')

B, G, R = cv2.split(image)

ret, thresh = cv2.threshold(G, 128, 255, cv2.THRESH_BINARY)
print(thresh.shape)

# 单通道复制为三通道  ...代替所有的::   3 增加后的通道数   2 轴
GGG = np.repeat(G[...,np.newaxis], 3, 2)
print(GGG.shape)

eye = np.bitwise_and(image, GGG)

# 1. 找到所有的点, 画点的最小外接矩形
coords = np.column_stack(np.where(thresh > 0))
coords = coords[:, ::-1] # x, y互换
min_rect = cv2.minAreaRect(coords)
box = cv2.boxPoints(min_rect)
box = np.int0(box)
eye1 = copy.deepcopy(eye)
box1 = cv2.drawContours(eye1, [box], 0, [0, 255, 0], 1)

# 2. 找轮廓, 包含所有轮廓的点
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contour = []
for cont in contours:
    contour.extend(cont)

min_rect = cv2.minAreaRect(np.array(contour))
box = cv2.boxPoints(min_rect)
box = np.int0(box)
eye2 = copy.deepcopy(eye)
box2 = cv2.drawContours(eye2, [box], 0, [0, 0, 255], 1)

cv2.imshow('eye1', box1)
cv2.imshow('eye2', box2)
cv2.waitKey(0)

Python opencv 找包含多个区域的最小外接矩形_第1张图片
Python opencv 找包含多个区域的最小外接矩形_第2张图片

你可能感兴趣的:(opencv)