Retrieving RGB vector from pixel in Julia

Viewed 470

I'm having a hard time figuring out how to retrieve the components of the RGB vector of a pixel in Julia. For example, if I have an image I call image and I pick a pixel, say image[230, 1566], then if I wanted, say, the green component of the RGB vector, my inclination is to just do RGB(image[230, 1566]).g. However, such a thing would return a string like 0.778N0f8. I know that means "Normalized with 8 fractional bits," but this is not what I want. I simply want the actual float as a number so I can perform other operations on it. Any idea how I can get around this? Thanks in advance!

1 Answers

To have a better understanding what is going on let us consider a pixel:

julia> using Colors

julia> pixel = colorant"purple"
RGB{N0f8}(0.502,0.0,0.502)

We can see that the RGB type by default uses the type N0f8 to store it values. Let us look inside.

julia> dump(pixel)
RGB{FixedPointNumbers.N0f8}
  r: FixedPointNumbers.N0f8
    i: UInt8 0x80
  g: FixedPointNumbers.N0f8
    i: UInt8 0x00
  b: FixedPointNumbers.N0f8
    i: UInt8 0x80

You can see that internally, in fact, a pixel holds a set of 3 unsigned 8 bit integer numbers named r, g, b that hold their value in the i field.

The correct way to access those values is however through red, green, blue methods rather than fields:

julia> dump(red(pixel))
FixedPointNumbers.N0f8
  i: UInt8 0x80

If you want to get as the floating point value you can do float(red(pixel))):

julia> dump(float(red(pixel)))
Float32 0.5019608f0

Note however that now the returned value is 4x larger than the original data (32 bits instead of 8).

If you rather want to get the raw data (which is 8 bits) you can do:

julia> reinterpret(red(pixel))
0x80

Hope that clears it all.

Related