小编gui*_*ges的帖子

如何对 python 图像(使用 numpy、opencv 或 PIL)的每个 PIXEL(不是每个 RGB 组件!)应用操作?

我试图以有效的方式对图像的所有像素应用一个函数(在我的具体情况下,我想对每个像素进行一些颜色近似,但我认为这与问题无关)。问题是,我找到了不同的方法来做到这一点,但它们都在像素的每个组件上应用一个函数,而我想做的是应用一个接收像素(而不是像素组件)的函数,这是 3 个 RGB 组件(我猜是一个元组,但只要我的函数中将这 3 个组件作为参数,我就不关心格式)。

如果您对我所拥有的感兴趣,这是解决我的问题的低效解决方案(工作正常,但太慢):

def closest_colour(pixel, colours):
    closest_colours = sorted(colours, key=lambda colour: colours_distance(colour, pixel))
    return closest_colours[0]

# reduces the colours of the image based on the results of KMean
# img is image open with opencv.imread()
# colours is an array of colours
def image_color_reduction(img, colours):
    start = time.time()
    print("Color reduction...")
    reduced_img = img.copy()[...,::-1]
    width = reduced_img.shape[0]
    height = reduced_img.shape[1]
    
    for x in range(width):
        for y in range(height):
            reduced_img[x,y] = closest_colour(reduced_img[x,y], colours) …
Run Code Online (Sandbox Code Playgroud)

python opencv numpy image-processing python-imaging-library

3
推荐指数
1
解决办法
1641
查看次数