[Numpy-discussion] Optimizing speed for large-array inter-element algorithms (specifically, color space conversion)
Arnar Flatberg
arnar.flatberg at gmail.com
Mon Jan 21 17:17:38 EST 2008
Hi Theodore
Probably not the fastest, but a full example of how you may vectorize your loop.
Ran just one test, and that speeded up the original code.
Example:
----------------
from numpy import empty_like
def vectorized_rgb2hsv(im):
"im is a (m, n, 3) array."""
im = im/255.
out = empty_like(im)
im_max = im.max(-1)
delta = im.ptp(-1)
s = delta/im_max
s[delta==0] = 0
index = im[:,:,0] == im_max # red is max
out[index, 0] = (im[index, 1] - im[index, 2] ) / delta[index]
index = im[:,:,1] == im_max # green is max
out[index, 0] = 2 + (im[index, 2] - im[index, 0] ) / delta[index]
index = im[:,:,2] == im_max # blue is max
out[index, 0] = 4 + (im[index, 0] - im[index, 1] ) / delta[index]
out[:,:,0] = (out[:,:,0]/6.0) % 1.0
out[:,:,1] = s
out[:,:,2] = im_max
out = (255.*out).astype(uint8)
return out
Timings (shape: 1202, 800, 3):
-----------------
code in first post:
%prun a = rgb2hsv.rgb2hsv(s)
1923207 function calls in 18.423 CPU seconds
removing loop:
%prun b = rgb2hsv.vectorized_rgb2hsv(s)
8 function calls in 4.630 CPU seconds
Arnar
More information about the NumPy-Discussion
mailing list