我正在用python制作一个图像和视频转换器。基本方法是:
创建一个列表,其中存储构成我的输出“调色板”的292种颜色。
创建一个dict作为以前颜色比较的缓存
将图像/帧缩小到更小的尺寸(最大宽度:132)
迭代图像中的每个像素。
对于每个像素,检查其颜色是否在缓存中如果是,请使用缓存中定义的调色板颜色。
如果在缓存中找不到像素的颜色,请使用algorithm here的变体将其与调色板列表中的292种颜色进行比较。
选择距离最小的调色板颜色。
所以我最后得到一个for循环,每次都调用颜色比较函数。这里有一个近似值:

possibles = [ list of color dicts here ]
match_cache = { }

def color_comparison( pixel, possibles ):
    closest_distance = INFINITY
    closest_possible = 0
    for possible in possibles:
        d = color_distance( pixel, possible )
        if d < closest_distance:
            closest_distance = d
            closest_possible = possible
    hash = pixel.makeHash()
    match_cache[hash] = closest_possible
    return closest_possible

def image_convert( image ):
    output = []
    for pixel in image:
        hash = pixel.makeHash()
        if hash in match_cache:
            output.append( match_cache[hash] )
        else:
            new_color = color_comparison( pixel, possibles )
            output.append( new_color )
    return output

我的问题是:我怎样才能加快速度?有没有更好的方法,而不是迭代每一个像素的每一个可能?

最佳答案

这~200种颜色是什么?解决方案可能取决于颜色分布。
在python dict中走得够快吗?字典的目的是搜索精确匹配,而不是检查所有项。也许,列表或数组是更好的选择?
但主要的问题是在所有可能的颜色之间进行彻底的搜索。
良好的数据结构可以大大加快搜索速度考虑八叉树,其中分离是为R,G,B颜色组件实现的。
Arbitrary example

10-07 19:12
查看更多