3

well i've seen some code to convert RGB to HSL; but how to do it fast in python.

Its strange to me, that for example photoshop does this within a second on a image, while in python this often takes forever. Well at least the code i use; so think i'm using wrong code to do it

In my case my image is a simple but big raw array [r,g,b,r,g,b,r,g,b ....]

I would like this to be [h,s,l,h,s,l,h,s,l .......]

Also i would like to be able to do hsl to rgb

the image is actually 640x 480 pixels; Would it require some library or wrapper around c code (i never created a wrapper) to get it done fast ?

user613326
  • 2,140
  • 9
  • 34
  • 63

3 Answers3

6

For manipulating image data, many use the Python Imaging Library. However, it doesn't handle HSL colour. Luckily, Python comes with a library called colorsys. Here's an example of colorsys being used to convert between colour modes on a per-pixel level: http://effbot.org/librarybook/colorsys.htm

colorsys also provides a function to convert HSL to RGB: http://docs.python.org/library/colorsys.html

Gavin Anderegg
  • 6,281
  • 2
  • 25
  • 35
  • the question specifies needing a way to do it fast – even vectorized with numpy, using colorsys is really slow, unless I'm missing something. – Markus Feb 01 '12 at 19:10
  • also another method that works, i prefer Paul's asnwer dough it gives me more math to think about and to improve about for my own goals, thanks for your answer – user613326 Nov 28 '12 at 22:55
  • @Markus it's very easy to modify the code to make it work on numpy arrays. Actually you just need to change min/max to np.min/np.max... – Shaohua Li Sep 06 '17 at 13:31
4

I wrote this RGB to HSV converter a little while back. It starts with a PIL image but uses numpy to do the array operations efficently. It could very easily be modified to do HSL. Let me know if you want the modified version.

Community
  • 1
  • 1
Paul
  • 42,322
  • 15
  • 106
  • 123
  • ehm i want to do it fast, i tried something like this but its slow in python to do this on a whole image, even if i do it with numpy arrays. – user613326 Feb 27 '11 at 13:55
  • @user613326: This converts a 640x480 image in 0.7 seconds on my laptop. How fast do you need it? I estimate a dedicated, compiled library will likely offer only a 3X improvement. – Paul Feb 27 '11 at 14:25
  • Despite its not HSL but HSV (which is near) i like the code example in it, more recently i've been looking to find related math to convert it to another format (not bound to real 360 degrees Dwords) from your code i might be able to rewrite that and then run a faster version (but less precise). – user613326 Nov 28 '12 at 22:53
1

One option is to use OpenCV. Their Python bindings are pretty good (although not amazing). The upside is that it is a very powerful library, so this would just be the tip of the iceberg.

You could probably also do this very efficiently using numpy.

Josh Bleecher Snyder
  • 8,262
  • 3
  • 35
  • 37