【问题标题】:Is there a way to make this code run faster有没有办法让这段代码运行得更快
【发布时间】:2021-10-13 13:36:30
【问题描述】:

如何在 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

【问题讨论】:

  • 是的。将字典转换为 numpy 数组并将其称为“查找表”,然后使用 numpy 索引进行查找。删除所有循环
  • 你会找到答案here
  • 我不太明白如何使用 numpy 索引进行查找@Christopher Rackwitz

标签: opencv image-processing deep-learning semantic-segmentation deeplab


【解决方案1】:

在这里

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 实现的,因此运行得更快

【讨论】:

  • 关于为什么这更快的上下文可能很有用。
  • 感谢您的指针,这是因为删除了 for 循环
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 2022-10-04
相关资源
最近更新 更多