# [Numpy-discussion] Optimizing speed for large-array inter-element algorithms (specifically, color space conversion)

Bruce Southey bsouthey@gmail....
Tue Jan 22 08:21:11 CST 2008

```Hi,
Also try NumExpr (http://www.scipy.org/SciPyPackages/NumExpr):
"The scipy.sandbox.numexpr package supplies routines for the fast
evaluation of array expressions elementwise by using a vector-based
virtual machine. "

However, this page is probably a little out of date.

Regards
Bruce

On Jan 21, 2008 4:17 PM, Arnar Flatberg <arnar.flatberg@gmail.com> wrote:
> 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
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
```