当我想使用 calcHist 生成图片特定范围内的像素数时,断言失败
Posted
技术标签:
【中文标题】当我想使用 calcHist 生成图片特定范围内的像素数时,断言失败【英文标题】:Assertion failed when I want to use calcHist to generate the number of pixels in a specific range of a picture 【发布时间】:2016-04-06 15:59:50 【问题描述】:我想使用 calcHist 计算特定颜色范围内的像素数。但是我收到以下错误:
OpenCV Error: Assertion failed (dims <= 2 && data && (unsigned)i0 < (unsigned)(size.p[0]*size.p[1]) && elemSize() == (((((DataType<_Tp>::type) & ((512 - 1) << 3)) >> 3) + 1) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> ((DataType<_Tp>::type) & ((1 << 3) - 1))*2) & 3))) in cv::Mat::at, file e:\opencv2.4\opencv\build\include\opencv2\core\mat.hpp, line 570
ZKB_shop.exe has triggered a breakpoint.
我的代码如下所示:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main(int argc, const char** argv)
Mat image = imread("D:\\obj\\138.jpg");
Mat img_hsv;
cvtColor(image, img_hsv, CV_BGR2HSV);
int hbins = 1;
int sbins = 1;
int vbins = 1;
int histSize[] = hbins,sbins,vbins ;
//H
float hranges[] = 0,20 ;
//S
float sranges[] = 100,255 ;
//V
float vranges[] = 107,245 ;
const float* ranges[] = hranges,sranges,vranges ;
MatND hist;
//chanels
int channels[] = 0,1,2 ;
calcHist(&img_hsv, 1, channels, Mat(), hist, 3, histSize, ranges);
cout << "Hist.dims = " << hist.dims << endl;
cout << "Value: " << hist.at<double>(0) << endl;
cout << "Hist.rows = " << hist.rows << endl;
cout << "Hist.cols = " << hist.cols << endl;
return 0;
我改编了官方教程中的代码:http://docs.opencv.org/3.1.0/d6/dc7/group__imgproc__hist.html#ga4b2b5fd75503ff9e6844cc4dcdaed35d 并添加一个频道,但我不知道为什么它不起作用。
我用的是VS2015+WIN10+OPENCV2.4.11
【问题讨论】:
【参考方案1】:你过于复杂了。
要获取给定颜色范围内的像素数,您可以:
-
使用
inRange
在给定颜色范围内创建值的掩码
计算掩码中非零像素的数量,使用countNonZero
代码:
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
// Read the image
Mat image = imread("path_to_image");
// Convert to HSV
Mat img_hsv;
cvtColor(image, img_hsv, CV_BGR2HSV);
// Define lower and upper ranges
Scalar lower(0, 100, 107);
Scalar upper(20, 255, 245);
// Create a mask with pixels in range
Mat1b mask;
inRange(img_hsv, lower, upper, mask);
// Count the number of non-black pixels
int cnz = countNonZero(mask);
cout << "# pixels in range " << cnz << endl;
return 0;
【讨论】:
以上是关于当我想使用 calcHist 生成图片特定范围内的像素数时,断言失败的主要内容,如果未能解决你的问题,请参考以下文章
仅考虑特定像素(而非完整图像)的OpenCV颜色直方图calcHist