Python Opencv 颜色范围直方图

Python Opencv Color range histogram

我在一个项目中工作,我想从给定图像中获取自定义直方图。

假设我想计算三种颜色的像素数:

  1. 浅棕色。
  2. 蓝色。
  3. 红色。

我发现很容易计算与具体颜色匹配的像素,但我想给颜色一个阈值,这就是我的问题。

我怎样才能做一个好的阈值来反射几乎浅棕色或几乎红色等...

谢谢。

一切都与您的 BINS 有关

来自 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.

引用的例子见[1]

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

这两个链接都值得通读,但实际上你可以做的是为你想要的范围设置多个 bin,比如浅棕色是 1-15(我不知道实际值)然后你可以选择你想要的颜色。

我找到了一个非常好的方法来解决我的问题:

  1. LAB colorspace 是比较颜色的不错的色彩空间。
  2. 平方差公式。

示例代码:

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)
         )

具有最低 deltaE 的像素与比较颜色在感知上最相似。

有了这个,就可以很容易地根据我要计算的颜色构建直方图。