代码是这样的:
Mat mat = imread("123.jpg");
cv::imshow("123.jpg",mat);
Mat hsv;
cvtColor(mat,hsv,COLOR_BGR2HSV);
Mat dst;
inRange(hsv,Scalar(0,0,49),Scalar(47,165,111),dst);
cout<<"dst channels:"<<dst.channels()<<endl;
int c0=0,c255=0,other=0;
for(int i=0;i<dst.rows;i++){
for(int j=0;j<dst.cols;j++){
int v = dst.at<uchar>(i,j);
if(v == 0){
c0++;
}else if(v == 255){
c255++;
}else{
other++;
}
}
}
cout<<"0 count:"<<c0<<",255 count:"<<c255<<",other value count:"<<other<<endl;
cv::erode(dst,dst,cv::Mat(),cv::Point(1,1),6);
cv::dilate(dst,dst,cv::Mat(),cv::Point(1,1),6);
cv::medianBlur(dst,dst,15);
cv::imshow("inRange",dst);
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat temp;
dst.copyTo(temp);
findContours(temp,contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE );
cout<<"contours size:"<<contours.size()<<endl;
cout<<"hierarchy size:"<<hierarchy.size()<<endl;
for (int index = 0; index >= 0; index = hierarchy[index][0]) {
cout<<"hierarchy at:"<<index<<","<<hierarchy[index]<<endl;
cv::drawContours(mat,contours,index,Scalar(120,255,0));
}
cv::imshow("contours",mat);
waitKey(0);
return 0;
我不知道为什么轮廓尺寸小于层次结构尺寸。事实上,应该有三个“外部”形状。似乎在输出轮廓中错过了一个形状。这个问题困扰了我一天,现在我会变得疯狂......任何人都知道为什么轮廓中只有两个元素?我做错了吗?
答案 0 :(得分:2)
这对我有用:
contours size:3
hierarchy size:3
hierarchy at:0,[1, -1, -1, -1]
hierarchy at:1,[2, 0, -1, -1]
hierarchy at:2,[-1, 1, -1, -1]
您的代码可能存在以下问题:
dst
可能未正确初始化dst
可能不是二进制文件,即可能包含与0
和255
不同的值代码:
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// Load image
Mat3b img = imread("path_to_image");
// Convert to grayscale
Mat1b bin;
cvtColor(img, bin, COLOR_BGR2GRAY);
// Binarize (remove jpeg artifacts)
bin = bin > 100;
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(bin.clone(), contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
cout << "contours size:" << contours.size() << endl;
cout << "hierarchy size:" << hierarchy.size() << endl;
for (int index = 0; index >= 0; index = hierarchy[index][0]) {
cout << "hierarchy at:" << index << "," << hierarchy[index] << endl;
cv::drawContours(img, contours, index, Scalar(120, 255, 0), 2);
}
imshow("Result", img);
waitKey();
return 0;
}
答案 1 :(得分:0)
我的VS工具已与..\opencv\build\x64\vc12\lib
相关联,我遇到了类似的问题。
我通过更改..\opencv\build\x86\vc12\lib
我在Windows 7上使用Visual Studio 2010.