# 二维, axis=0, 按行比较, [1, 0, 0]有两个,只返回一个
>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
>>> np.unique(a, axis=0)
array([[1, 0, 0], [2, 3, 4]])
# 三维矩阵, 按通道比较,三个通道值算作一组,和其他组比较
np.unique(mask_label.reshape(-1, 3), axis=0)
# 按通道查询某个值,比如查询三维矩阵中某个颜色所在位置,并赋其他颜色
equality = np.equal(multi_object_mask, mask_bgr_color)
multi_object_mask[np.all(equality, axis=-1)] = [255, 0, 0] # 赋蓝色
# np.unique(mask_label.reshape(-1, 3), axis=0) 图片大小(4096,1700), 需要3s
# 下面的只需要0.003s
def find_colors(mask_label):
gray_mask_label = cv2.cvtColor(mask_label, cv2.COLOR_BGR2GRAY)
gray_mask_label[gray_mask_label > 0] = 255
cnts, _ = cv2.findContours(gray_mask_label, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)
mask_color_list = []
for cnt in cnts:
M = cv2.moments(cnt)
center_x = int(M["m10"] / M["m00"])
center_y = int(M["m01"] / M["m00"])
mask_color = mask_label[center_y, center_x]
mask_color_list.append(mask_color)
return mask_color_list