Search code examples
imagecolorstype-conversionjuliacolor-space

Converting images from RGB to HSL and back again with julia


I have been trying to open some RGB images, view the data as a 2D array of HSL pixels, manipulate pixels in HSL space, convert back to RGB and write manipulated image to file. However I don't quite understand how the conversions in the (awesome) julia packages Color and Images work.

For example, I expect the code below (partially written following the example from this SO question) to write something very much like this image file (as test_1.png and test_2.png):

Test image (shag)

However, the code below actually produces this much darker image instead:

Test image after conversion from RGB to HSL and back to RGB

How should I re-arrange the arrays or images to get the output I expect?

using Color, Images

# Download file, read it in, convert colourspace to HSL and recast as array
fname=download("https://farm9.staticflickr.com/8725/17074451907_2381037c7d_m_d.jpg")
rgb=imread(fname)
hsl=convert(Image{HSL},float32(rgb))
hslArr=reinterpret(data(hsl))

# I would like to manipulate HSL data here...

# Two ways to convert manipulated array back to HSL image
hsl_1=Image(hslArr; colorspace="HSL", colordim=1, spatialorder=["x","y"])
hsl_2=reinterpret(HSL{Float32},hslArr)

# Two ways to convert HSL image to RGB image 
rgb_1=convert(Image{RGB},hsl_1)
rgb_2=convert(Array{RGB{Float32}},hsl_2)

# Finally, write images to file
imwrite(rgb_1,"test_1.png")
imwrite(rgb_2,"test_2.png")

UPDATE

Thanks to @rickhg12hs finding bug in the Color.jl module, I get expected output from code above after the following steps:

  1. Fork the source repository for Color.jl on github
  2. Correct the conversion function (as below), pushing changes to my fork of Color.jl
  3. Remove the default Color.jl module that comes with julia
  4. Install my forked package using Julia's git mechanism.
  5. Restart julia

I haven't been able to figure out how to install a forked version of a module in parallel with a previous version, but executing the following (followed by restarting julia) should temporarily fix the bug:

Pkg.rm("Color")
Pkg.clone("https://github.com/CnrLwlss/Color.jl.git","Color")
Pkg.checkout("Color","master")

Will need to switch back to original Color module once pull request goes through.


Solution

  • Until Color.jl gets updated and more testing implemented/passed, you can make a single character change in Color/src/conversions.jl to most likely fix this particular issue. Change - to + on line 156.

       150  # Everything to HSL
       151  # -----------------
       152  
       153  function convert{T}(::Type{HSL{T}}, c::AbstractRGB)
       154      c_min = min(c.r, c.g, c.b)
       155      c_max = max(c.r, c.g, c.b)
       156      l = (c_max + c_min) / 2     # <-- Changed '-' to '+'
    

    On my machine, your HSL converted bird looks great now!