计算图片中蓝色像素的数量 [英] Calculating the number of blue pixels in a picture
问题描述
我是openCV和Python的新手,对此有一个疑问.我正在尝试查找图片的蓝色像素数量,因此我可以将它们用作阈值,以便与其他图片进行比较.我尝试浏览文档,但找不到任何有用的东西.
I am new to openCV and Python and a have a question concerning it. I am trying to find the amount of blue pixels of a picture so i can use them as a threshold in order to compare other pictures with it. I have tried looking through the documentation but i couldn't find anything helpful yet.
任何人都可以提供提示或帮助吗?
Can anyone give a hint or some help?
BLUE_MAX = np.array([0, 0, 200], np.uint8)
BLUE_MIN = np.array([50, 50, 255], np.uint8)
dst = cv.inRange(img, BLUE_VALUE_MIN, BLUE_VALUE_MAX)
no_blue = cv.countNonZero(dst)
print('The number of blue pixels is: ' + str(no_blue))
-因此,根据您的建议,我构建了以下功能,但运行时得到的只是一张空白图片.
-So based on your recommendation I built the following function but all I get when I run it is a blank picture.
推荐答案
要计算RGB图像中的蓝色像素,您只需执行以下操作
For counting blue pixel in a RGB image you can simply do the following
- 范围将源图像滤除为蓝色成分二进制图像.
- 使用函数 countNonZero 计数二进制图像中的非零像素a>.
- Inrange the source image to filter out blue component to a binary image.
- Count non zero pixel in the binary image using the function countNonZero.
您可以参考下面的C ++代码以了解操作方法
You can refer below C++ code for how to do it
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat src,dst;
src = imread("rgb1.jpg",1);
inRange(src, Scalar(200,0,0), Scalar(255,50,50), dst); //In range with approximate blue range
cout<<"No of blue pixels---->"<<countNonZero(dst)<<endl;
imshow("src",src);
imshow("out",out);
waitKey(0);
return 0;
}
-
这是有效的python代码
-
Here is the working python code
import cv2
import numpy as np
img = cv2.imread("bgr.png")
BLUE_MIN = np.array([0, 0, 200], np.uint8)
BLUE_MAX = np.array([50, 50, 255], np.uint8)
dst = cv2.inRange(img, BLUE_MIN, BLUE_MAX)
no_blue = cv2.countNonZero(dst)
print('The number of blue pixels is: ' + str(no_blue))
cv2.namedWindow("opencv")
cv2.imshow("opencv",img)
cv2.waitKey(0)
希望这就是您想要的.....
Hope this is what you looking for.....
@kigurai在OpenCV下方评论时,以BGR顺序考虑图像,并且我为BLUE_MIN和BLUE_MAX数组给出了错误的顺序. 因此,在上面的代码行中
As @ kigurai commented below OpenCV consider image in BGR order and I gave wrong order for BLUE_MIN and BLUE_MAX array. So in the above code the lines
BLUE_MIN = np.array([0, 0, 200], np.uint8)
BLUE_MAX = np.array([50, 50, 255], np.uint8)
应更改为
BLUE_MIN = np.array([200, 0, 0], np.uint8) // minimum value of blue pixel in BGR order
BLUE_MAX = np.array([255, 50, 50], np.uint8)// maximum value of blue pixel in BGR order
这篇关于计算图片中蓝色像素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!