python求出mask的bbox坐标,mask的轮廓部分,凸包

def extract_bboxes(mask):
    """Compute bounding boxes from masks.
    mask: [height, width, num_instances]. Mask pixels are either 1 or 0.

    Returns: bbox array [num_instances, (y1, x1, y2, x2)].
    """
    boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32)
    for i in range(mask.shape[-1]):
        m = mask[:, :, i]
        # Bounding box.
        horizontal_indicies = np.where(np.any(m, axis=0))[0]
        vertical_indicies = np.where(np.any(m, axis=1))[0]
        if horizontal_indicies.shape[0]:
            x1, x2 = horizontal_indicies[[0, -1]]
            y1, y2 = vertical_indicies[[0, -1]]
            # x2 and y2 should not be part of the box. Increment by 1.
            x2 += 1
            y2 += 1
        else:
            # No mask for this instance. Might happen due to
            # resizing or cropping. Set bbox to zeros
            x1, x2, y1, y2 = 0, 0, 0, 0
        x1 = 0 if x1 < 0 else x1
        y1 = 0 if y1 < 0 else y1
        y2 = mask.shape[0] - 1 if y2 >= mask.shape[0] else y2
        x2 = mask.shape[1] - 1 if x2 >= mask.shape[1] else x2
        boxes[i] = np.array([y1, x1, y2, x2])
    return boxes.astype(np.int32)
    
cols_status = np.any(image_np, axis=0)
x_index = np.where(cols_status)[0]
#
rows_status = np.any(image_np, axis=1)
y_index = np.where(rows_status)[0]
print(x_index[0], x_index[-1], y_index[0], y_index[-1])
#
top_left = (x_index[0], y_index[0])
right_bottom = (x_index[-1], y_index[-1])

image_np = image_np.reshape((image_np.shape[0], image_np.shape[1], 1))
bbox = extract_bboxes(image_np)

plt.gca().add_patch(plt.Rectangle(xy=(bbox[0][1], bbox[0][0]),
                                  width=bbox[0][3] - bbox[0][1],
                                  height=bbox[0][2] - bbox[0][0],
                                  edgecolor='red',
                                  fill=False, linewidth=2))

在这里插入图片描述

 img = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
 contours, hierarchy = cv2.findContours(np.array(image_np, np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
 print(len(contours))
 for i in range(len(contours)):
     cv2.drawContours(img, contours, i, (255, 255, 0), 5)
     cv2.imshow('contour-%d' % i, img)
     cv2.waitKey()

 cv2.destroyAllWindows()
 plt.subplot(1, 2, 1)
 plt.imshow(image_np)
 plt.show()

求出mask的每一个部分

chull = morphology.convex_hull_image(image_np)
chull = np.where(chull == True, 1, 0)
chull = chull.reshape((chull.sha# chull = morphology.convex_hull_image(image_np)
chull = np.where(chull == True, 1, 0)
chull = chull.reshape((chull.shape[0], chull.shape[1], 1))pe[0], chull.shape[1], 1))

求出mask的凸包

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骨子带刺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值