计算mask外接矩阵
########示例############
import numpy as np
# 生成一个随机掩模
mask = np.zeros((100, 100))
mask[20:40, 30:60] = 1
# 获取掩模内像素点坐标
coords = np.where(mask)
# 获取矩形区域的左上角和右下角坐标
x_min, y_min = np.min(coords, axis=1)
x_max, y_max = np.max(coords, axis=1)
# 获取矩形区域
rect_area = mask[x_min:x_max, y_min:y_max]
将示例与SLIC超像素结合,达到将每一块超像素都截取出来的结果:
########
#提取mask区域
import cv2
import numpy as np
from skimage.segmentation import slic
img = cv2.imread('F:\graduate study\code\SLIC\Super Pixel\\2_try\POS_IMAGE\\321.jpg')
segments = slic(img, n_segments=800, compactness=20, enforce_connectivity=True, convert2lab=True)
# loop over the unique segment values
for (i, segVal) in enumerate(np.unique(segments)):
# construct a mask for the segment
mask = np.zeros(img.shape[:2], dtype="uint8")
mask[segments == segVal] = 255
# 获取掩模内像素点坐标
coords = np.where(mask)
# 获取矩形区域的左上角和右下角坐标
x_min, y_min = np.min(coords, axis=1)
x_max, y_max = np.max(coords, axis=1)
print(x_min, y_min,x_max, y_max )
# 获取矩形区域
mask_area = img[x_min:x_max, y_min:y_max]
cv2.imshow("img_slic", mask_area)
cv2.waitKey(0)