Iris G.
Iris G.

Reputation: 463

Python Opencv Color range histogram

I'm working in a project in which I would like to get a custom histogram from a given image.

Let's say I want to count the number of pixels of three colors:

  1. Light brown.
  2. Blue.
  3. Red.

I find easy to count the pixel that matchs a concret color, But I would like to give the colors a threshold, and here is my problem.

How can I do a good threshold that will reflect almost Light brown color or almost red, etc...

Thanks.

Upvotes: 0

Views: 1820

Answers (2)

Iris G.
Iris G.

Reputation: 463

I found a really nice method to solve my problem:

  1. LAB colorspace is a nice colorspace to compare colors.
  2. Difference of squares formula.

Example code:

red_bgr = (0,0,255) # red pixel
pixel = (2,2,245) # pixel to compare 
red_lab = cv2.cvtColor(pixel1, cv2.COLOR_BGR2LAB)
pixel_lab = cv2.cvtColor(pixel1, cv2.COLOR_BGR2LAB)
deltaE = sqrt(abs(red_lab[0] - pixel_lab[0])**2 +
              abs(red_lab[1] - pixel_lab[1])**2 +
              abs(red_lab[2] - pixel_lab[2])**2)
         )

Pixels with lowest deltaE are the most perceptually similar to the compared color.

Having this it's easy to build a histogram based on the colors I want to count.

Upvotes: 0

GPPK
GPPK

Reputation: 6666

It's all about your BINS

from here

BINS :The above histogram shows the number of pixels for every pixel value, ie from 0 to 255. ie you need 256 values to show the above histogram. But consider, what if you need not find the number of pixels for all pixel values separately, but number of pixels in a interval of pixel values? say for example, you need to find the number of pixels lying between 0 to 15, then 16 to 31, ..., 240 to 255. You will need only 16 values to represent the histogram. And that is what is shown in example given in OpenCV Tutorials on histograms.

The example that the quote refers to is shown in [1]

[1] - http://docs.opencv.org/doc/tutorials/imgproc/histograms/histogram_calculation/histogram_calculation.html#histogram-calculation

Both of those links are worth reading through but effectively what you can do is set a number of bins for the ranges that you want, say light brown is 1-15 (i don't know the actual values) then you can threshold for the colours you want.

Upvotes: 1

Related Questions