我如何在numpy中编写这个for循环以使其运行得更快我试图将灰度标签值0-7转换为具有相应颜色的彩色图像
def label_img_to_color(img):
label_to_color = {
0: [0, 0,0],
1: [244, 35,232],
2: [ 70, 70, 70],
3: [102,102,156],
4: [190,153,153],
5: [153,153,153],
6: [250,170, 30],
7: [220,220, 0],
}
img_height, img_width = img.shape
img_color = np.zeros((img_height, img_width, 3))
for row in range(img_height):
for col in range(img_width):
label = img[row, col]
img_color[row, col] = np.array(label_to_color[label])
return img_color
在这里
def label_img_to_color_20(img):
img=img.astype(np.uint8)
lut=np.ones((256,1,3),dtype=np.uint8)
ine = np.array([[
[128, 64,128],#road 0
[244, 35,232],#sidewalk 1
[ 70, 70, 70],#building 2
[190,153,153],#wall 3
[153,153,153],#fence 4
[250,170, 30],#pole 5
[220,220, 0],#traffic light 6
[107,142, 35],#traffic sign 7
]])
lut[0:8,:,:]=ine.reshape(8,1,3)
img_color=cv2.applyColorMap(img,lut)
return img_color
这是更快的方法如果有人遇到这样的问题不要在图像上使用for循环总是使用numpy或opencv函数来完成因为它们是用C实现的,因此运行得更快