import numpy as np
def colormap(rgb=False):
color_list = np.array(
[
0.000, 0.447, 0.741,
0.850, 0.325, 0.098
]
).astype(np.float32)
color_list = color_list.reshape((-1, 3)) * 255
if not rgb:
color_list = color_list[:, ::-1]
return color_list
color_list = colormap(rgb=True) / 255
for i in range(len(color_list)):
color_mask = color_list[i, 0:3]
1. cv2.drawContours(im, contours, -1, color_mask, -1)
2. cv2.drawContours(im, contours, -1, tuple(color_mask), -1)
3. cv2.drawContours(im, contours, -1, tuple(color_mask.astype(np.int32)), -1)
4. cv2.drawContours(im, contours, -1,(int(color_mask[0]),int(color_mask[1]),int(color_mask[2])), -1)
colormap是一个nparray类型的颜色数组,当我想使用它依次给不同的轮廓作颜色填充时,遇到了如题的bug.
编号1,2,3,4表示我尝试的改法,4是正确的
1是最初的代码
以为是该函数只接受tuple类型的,于是将nparray改成tuple得到代码2再次报错
百度了bug的意思是指传入的color值不是数值类型的,才发现数组里是浮点型于是再进行类型转换得到第3行代码依旧报错,尝试将其值以及类型输出发现确实是tuple且是整数格式如(100,110,120),这时我已蒙
最后尝试直接用数值型的tuple如(1,2,3)传入发现不会报错,才醒悟到数据类型此时是np.int32,而接受的应该是python的内置类型'int'
笔记: cv2函数接受的color颜色的数据类型应该是三个元素的tuple且其中元素的数据类型是python的内置类型'int',其他如np.int32会报错