Create a colour histogram from an image file

Viewed 142

I'd like to use Nim to check the results of my Puppeteer test run executions. Part of the end result is a screenshot. That screenshot should contain a certain amount of active colours. An active colour being orange, blue, red, or green. They indicate activity is present in the incoming data. Black, grey, and white need to be excluded, they only represent static data.

I haven't found a solution I can use yet.

import stb_image/read as stbi

var
  w, h , c:int
  data: seq[uint8]
  cBin: array[256,int] #colour range was 0->255 afaict
data = stbi.load("screenshot.png",w,h,c,stbi.Default)
for d in data:
  cBin[(int)d] = cBin[(int)d] + 1
echo cBin

Now I have a uint array, which I can see I can use to construct a histogram of the values, but I don't know how to map these to something like RGB values. Pointers anyone?

Is there a better package which has this automagically, I didn't spot one.

1 Answers

stbi.load() will return a sequence of interleaved uint8 color components. The number of interleaved components is determined either by c (i.e. channels_in_file) or desired_channels when it is non-zero.

For example, when channels_in_file == stbi.RGB and desired_channels == stbi.Default there are 3 interleaved components of red, green, and blue.

[
# r    g    b
  255, 0,   0,   # Pixel 1
  0,   255, 0,   # Pixel 2
  0,   0,   255, # Pixel 3
]

You can process the above like:

import colors
for i in countUp(0, data.len - 3, step = stbi.RGB):
  let
    r = data[i + 0]
    g = data[i + 1]
    b = data[i + 2]
    pixelColor = colors.rgb(r, g, b)
  echo pixelColor

You can read more on this within comments for the stb_image.h.

Related