Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 有没有办法改进这个pygame颜色过滤算法_Arrays_Python 3.x_Numpy_Pygame - Fatal编程技术网

Arrays 有没有办法改进这个pygame颜色过滤算法

Arrays 有没有办法改进这个pygame颜色过滤算法,arrays,python-3.x,numpy,pygame,Arrays,Python 3.x,Numpy,Pygame,我制作这个程序是为了快速有效地将pygame图像过滤到选定的调色板。问题是,它真的很慢 我做了一些事情来提高它的速度,例如删除搜索最近颜色的函数中的sqrt操作(因为它没有做任何有用的事情),并使用.unique使NumPy数组更快地获取唯一行。问题是,它仍然很慢。我希望它能实时工作,而不是像蜗牛一样慢 有什么方法可以改进这个算法来实现这一点吗?或者,除非我降低到像C这样的较低级别,否则这是不可能的?这是我的密码: import pygame import numpy as np def un

我制作这个程序是为了快速有效地将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()

使用纯python可能无法获得这样的性能,不。选项包括numba和Cython,或者在scipy中预构建颜色缩放解决方案。我明白了,使用pygame和opengl并使用opengl着色器可以实现这一点吗?还是会太慢?如果没有,我以前没有使用过cython或numba,我可以在它们上面安装moderngl和pygame吗?很有可能scipy已经具备了您想要的图像处理方面的所有功能。Cython和numba是将python代码编译成C速度的方法。另一方面,着色器可能已经足够了是的。听起来不错,我会更多地研究scipy,看看我是否能用它快速完成所有事情,如果不能,我会制作一个opengl着色器。这对找到相似的颜色可能会有帮助。