0
我有一个非常简单的方法,将RGB图像转换为HSL并调整色相。这对于小图像文件来说工作速度相对较快,但大图像文件需要数分钟才能处理。我将imgdata
转换为一个numpy数组,但是这似乎并没有加速它的发展。我是否只需要在循环内部使用numpy函数来加速呢?我无法准确找到循环内部的瓶颈,因为它只是相当简单的数学计算。加快numpy图像处理计算
from colorsys import rgb_to_hls, hls_to_rgb
from numpy import array
def reload_img():
global img, sizew, sizeh, maxsize, imgdata
img = Image.open(IMAGE_SRC)
sizew, sizeh = img.size
maxsize = ((sizew/2)**2 + (sizeh/2)**2)**0.5
imgdata = list(img.getdata())
# Convert to numpy array
imgdata = array(imgdata)
IMAGE_SRC = "test.jpg"
reload_img()
# Adjust Hue
for i in range(0,len(imgdata)):
r,g,b = imgdata[i]
r /= 255.0
g /= 255.0
b /= 255.0
(h, l, s) = rgb_to_hls(r,g,b)
h = .50
imgdata[i] = hls2rgb((h,l,s))
numpy的技巧是不使用python中的'for循环'。 Numpy默认以迭代的方式遍历ndarray元素,所以试着想出一种分割和使用布尔模板的方法,你会看到巨大的性能提升。 – willnx
我有一段时间有点类似的问题,但它可以帮助你:http://stackoverflow.com/questions/5414638/using-numpy-and-pil-to-convert-56516bit-color-to-88824bit-color - 它曾经是一个for循环,但你可以看到如何删除和数组操作被使用 – pyInTheSky
另外,如果你可以安装它,[scikit image](http://scikit-image.org/docs/ dev/api/skimage.color.html#rgb2hsv)已经通过Numpy解决了这个问题。 – willnx