arrays - 有没有办法改进这个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()
解决方案
推荐阅读
- vhdl - 如何在vivado的详细原理图设计中去除OBUF?
- linux - Docker 网络接口未发布到主机名称空间
- ffmpeg - FFMPEG 添加另一个命令
- php - 显示从 MySQL 到 Laravel 的 json 类型数据
- gsm - 使用 AT 命令通过 GSM 模块中的 UART 传输音频和 3G 数据
- javascript - jquery blueimp fileupload 将画布图像预览附加到 div
- android - 如何伪造蓝牙遥控器?
- haskell - 我可以在 Haskell 上使用 let in 守卫吗?
- http - 移动设备上的 Ionic 4 CORS 问题
- android - 为什么在使用bmob时无法调用signUp和login方法?