简体   繁体   English

在 Python 中重新映射 OpenCV 中的像素值的最快方法是什么?

[英]What's the fastest way to remap pixel values in OpenCV in Python?

I have a single channel image gray_image , with pixels values [0.. 255] and a lookup table mapping those values to colors:我有一个单通道图像gray_image ,像素值[0.. 255]和一个查找表将这些值映射到 colors:

lookup = {
 0: [0, 0, 0],
 1: [23, 54, 35],
 ...
 255: [200, 52, 20],
}

What is the fastest way to create a new 3 channel image where each pixel is colored based on the lookup of its value in the original images, eg创建一个新的 3 通道图像的最快方法是什么,其中每个像素都根据在原始图像中查找其值进行着色,例如

color_image[y, x] = lookup[gray_image[y, x]]

Instead of iterating through every pixel and setting it individually?而不是遍历每个像素并单独设置它?

Assuming that the keys of the lookup table are properly ordered, you could convert the dictionary into an array and then apply NumPy's advanced indexing like this:假设查找表的键排序正确,您可以将字典转换为数组,然后像这样应用 NumPy 的高级索引

import numpy as np

palette = np.array([row for row in lookup.values()])
color_image = palette[gray_image]

If the keys of your dictionary are not ordered, the code above won't work.如果字典的键没有排序,上面的代码将不起作用。 In that case you could convert the dictionary into an array as follows:在这种情况下,您可以将字典转换为数组,如下所示:

palette = np.zeros(shape=(256, 3), dtype=np.uint8)
for key in lookup.keys():
    palette[key] = lookup[key]

This approach implicitly defines a default value of [0, 0, 0] , ie if the lookup table does not contain a certain index, let's say n , then those pixels with gray level n will be mapped to [0, 0, 0] (black).这种方法隐式定义了一个默认值[0, 0, 0] ,即如果查找表不包含某个索引,比如说n ,那么那些灰度为n的像素将被映射到[0, 0, 0] (黑色的)。

palette = np.array([lookup[index] for index in range(256)], dtype=np.uint8)
color_image = palette[gray_image]

the other answer didn't make sure to sort the dictionary by key (python dicts only recently got a stable order of pairs) and it didn't make sure that all index values exist.另一个答案没有确保按键对字典进行排序(python dicts 最近才获得稳定的对顺序)并且它没有确保所有索引值都存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM