首页 > 解决方案 > 有没有办法改进这个pygame滤色器算法

问题描述

我制作了这个程序来快速有效地将 pygame 图像过滤到选定的调色板。问题是,它真的很慢。

我做了一些事情来提高它的速度,例如删除搜索最近颜色的函数中的 sqrt 操作(因为它没有做任何有用的事情)并.unique尝试使 NumPy 数组更快地获得唯一行。问题是,它仍然很慢。我希望它能够实时工作,而不是以蜗牛的速度。

有什么办法可以改进这个算法来实现这个吗?或者除非我降到 C 之类的较低级别,否则这是不可能的吗?这是我的代码:

import pygame
import numpy as np

def unique_void_view(a):
    return (
        np.unique(a.view(np.dtype((np.void, a.dtype.itemsize * a.shape[1]))))
        .view(a.dtype)
        .reshape(-1, a.shape[1])
    )

def closest(colors,color):
    colors = np.array(colors)
    color = np.array(color)
    distances = (np.sum((colors-color)**2,axis=1))
    index_of_smallest = np.where(distances==np.amin(distances))
    smallest_distance = colors[index_of_smallest]
    return smallest_distance


def ApplyFilter(Image,Colors):
        
        I = pygame.surfarray.array3d(Image)
        
        R = pygame.surfarray.pixels_red(Image)
        G = pygame.surfarray.pixels_green(Image)
        B = pygame.surfarray.pixels_blue(Image)
        A = pygame.surfarray.pixels_alpha(Image)
        I = (np.dstack((R,G,B,A)))
        I = I.reshape(-1, I.shape[2])

        I = unique_void_view(I)
        
        P = pygame.PixelArray(Image)

        for i in I:
            p = (i[0],i[1],i[2],i[3])
            q = closest(Colors,p)
            q = q[0][0],q[0][1],q[0][2],q[0][3]
            P.replace(p,q)

        return P.make_surface()

标签: arrayspython-3.xnumpypygame

解决方案


推荐阅读