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的凸包