"Crunch" RGB pixels into 0-1 range

Hi,

I’m messing around with image generation in Julia. I just realized that some of the pixels I’m generating have red, green, or blue values outside of the range [0,1]. For example, one of my pixels looks like RGB{Float64}(2.222500068146143,0.5746785271458048,2.1358479996207556). This image actually shows up great with imshow(), but when I go to save it as a .PNG file, the file turns out corrupted. Is there a quick way to “crunch” all the n0f8 values in my image into a 0-1 range? I could write a nested for loop, but it’s kinda ugly and I’d like something more efficient.

Broadcast clamp o some_function?

It seems that ImageInTerminal.jl clamps the values to 0 and 1, which you could do with:

clamp!(channelview(x), 0, 1)

There are other potentially useful approaches to this. If you know the scale of the floating point values used in your images, you could just subtract the minimum value from each color and then divide by the maximum range:

crunch!(x, lo, hi) = (c = channelview(x); c .-= lo; c ./= (hi - lo))

or even

crunch!(x) = (c = channelview(x); (lo, hi) = extrema(c); c .-= lo; c ./= (hi - lo))

depending on your use-case.

Hey, I ended up figuring it out by reading the error message from when I tried to save the image. What I wanted (saving the image so it looks like the output from imshow()) is achievable with save("image.png",map(clamp01nan, img)). Hope this helps someone else!

1 Like