[Numpy-discussion] rgb_to_hsv in scipy.misc ? (was: Optimizing speed for large-array inter-element algorithms (specifically, color space conversion))
Nicolas Pinto
pinto at mit.edu
Wed Feb 18 13:36:34 EST 2009
Hello,
Would it be possible to include the following rgb to hsv conversion code in
scipy (probably in misc along with misc.imread, etc.) ?
What do you think?
Thanks in advance.
Best regards,
--
Nicolas Pinto
Ph.D. Candidate, Brain & Computer Sciences
Massachusetts Institute of Technology, USA
http://web.mit.edu/pinto
#
------------------------------------------------------------------------------
import numpy as np
def rgb_to_hsv_arr(arr):
""" fast rgb_to_hsv using numpy array """
# adapted from Arnar Flatberg
# http://www.mail-archive.com/numpy-discussion@scipy.org/msg06147.html
# it now handles NaN properly and mimics colorsys.rgb_to_hsv output
arr = arr/255.
out = np.empty_like(arr)
arr_max = arr.max(-1)
delta = arr.ptp(-1)
s = delta / arr_max
s[delta==0] = 0
# red is max
idx = (arr[:,:,0] == arr_max)
out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
# green is max
idx = (arr[:,:,1] == arr_max)
out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0] ) / delta[idx]
# blue is max
idx = (arr[:,:,2] == arr_max)
out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1] ) / delta[idx]
out[:,:,0] = (out[:,:,0]/6.0) % 1.0
out[:,:,1] = s
out[:,:,2] = arr_max
# rescale back to [0, 255]
out *= 255.
# remove NaN
out[np.isnan(out)] = 0
return out
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090218/8b9ca94c/attachment.html>
More information about the NumPy-Discussion
mailing list