Mat 以矩阵的正常行/列方式索引,所以你想要mat.at<uchar>(y, x)
, not mat.at<uchar>(x, y)
,否则会导致混乱。
您所在的地方:
vector<Point>::iterator it;
it = vect1.begin();
...
for(...)
vect1.insert(it,vectN[i]);
如果插入导致缓冲区被重新分配,这将会中断,因为它随后指向一些已被释放的内存,或者可能被重新分配给其他东西。
而是使用
vect1.insert(vect1.begin(),vectN[i]);
(这将给出与您的程序似乎执行的操作略有不同的顺序)或使用push_back()
真正获得广度优先的行为。
最大的问题是在 search8Neighbor() 中。你在哪里有uchar p2 = mat.at<uchar>(startPoint.x-1, startPoint.y);
如果 startPoint 引用图像边缘的像素会发生什么?您将引用图像外部的像素,并且程序将偏离,直到发生异常。在这里,您需要检查您在图像中的位置,并确保邻域中不包含图像外部的像素。
EDIT我不相信如果按照我所说的进行更改,代码将无法工作。
我已经实施了修复并且它有效:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include <opencv2/legacy/compat.hpp>
#include <opencv2/core/core.hpp>
#include <iostream>
#include <cmath>
#include <list>
using namespace cv;
using namespace std;
// Find the 8-neighbors of a point from image.
vector<Point> search8Neighbor(cv::Mat mat,Point startPoint)
{
vector<Point> neighbors;
vector<Point> offsets;
offsets.push_back(Point(-1, 0)); // p2
offsets.push_back(Point(-1, 1)); // p3
offsets.push_back(Point( 0, 1)); // p4
offsets.push_back(Point( 1, 1)); // p5
offsets.push_back(Point( 1, 0)); // p6
offsets.push_back(Point( 1, -1)); // p7
offsets.push_back(Point( 0, -1)); // p8
offsets.push_back(Point(-1, -1)); // p9
vector<Point>::iterator it;
for(it = offsets.begin(); it < offsets.end(); ++it)
{
if(!((it->x < 0 && startPoint.x == 0)
|| (it->y < 0 && startPoint.y == 0)
|| (it->x > 0 && startPoint.x == mat.cols - 1)
|| (it->y > 0 && startPoint.y == mat.rows - 1)))
{
Point p(startPoint + *it);
if(mat.at<uchar>(p) == 255)
neighbors.push_back(p);
}
}
return neighbors;
}
//this method return a vector of points from a skeleton that contains all the points
// between a start point "peak" and an end point
//this method use the idea of Breadth first search
vector<Point> traceLine(Mat img , Point peak)
{
vector<Point> vect1;
vector<Point> vect2;
img.at<uchar>(peak.y, peak.x)=0;//
vect1.push_back(peak);//add peak to vect1
while(vect1.size() != 0)
{
Point p=vect1[0];
vect1.erase(vect1.begin());
vect2.push_back(p);
vector<Point> vectN;
vectN = search8Neighbor(img, p);
//cout<< " vectN.size()=" << vectN.size()<<endl;
for(int i = 0; i < int(vectN.size()); ++i)
{
img.at<uchar>(vectN[i].y, vectN[i].x)=0;
vect1.push_back(vectN[i]);
}
}
return vect2;
}
int main( int argc, char** argv )
{
cv::Mat im = cv::imread("aa.jpg",0);
if (im.empty())
return -1;
cv::Mat img;
cv::threshold(im, img, 155, 255, CV_THRESH_BINARY);
imshow("thresholded image",im);
vector<Point> vect1;
Point p(3, 32);
uchar u = img.at<uchar>(p.x, p.y);
if(img.at<uchar>(p) == 255)
vect1 = traceLine(img, p);
Mat output(im.rows, im.cols, CV_8UC3, Scalar(0, 0, 0));
vector<Point>::iterator it;
for(it = vect1.begin(); it < vect1.end(); ++it)
{
Vec3b green(0, 255, 0);
output.at<Vec3b>(*it) = green;
}
imshow("output", output);
cv::waitKey();
return 0 ;
}