itr = contours.erase(itr),老是运行内存出错

在网上看的寻找轮廓的程序,却在itr = contours.erase(itr)一直报错,分析语法什么的没有问题,多次尝试无果,调了一天,最终大神春帮忙,发现很有可能是vs版本跟opencv配置的问题,配置时opencv的环境路径为;E:\opencv\build\x86\vc10\bin;而我使用的版本实际上应该为v12,最后重新配置一遍opencv后问题得到成功解决,果然一个bug让某人调了一整天,记录下来,运行成功

#include 
//#include "cv.h"
#include "opencv2/imgproc/imgproc.hpp"  
#include "opencv2/highgui/highgui.hpp"  
#include"opencv2/opencv.hpp"


using namespace cv;
using namespace std;

vector<vector > contours;   //轮廓数组  
vector  centers;    //轮廓质心坐标   
vector<vector >::iterator itr;  //轮廓迭代器  
vector::iterator  itrc;    //质心坐标迭代器  
vector<vector > con;    //当前轮廓  


int main()
{
    double area;
    double minarea = 100;
    double maxarea = 0;
    Moments mom; // 轮廓矩  
    Mat image, gray, edge, dst;
    //namedWindow("origin");
    //namedWindow("connected_region");

    image = imread("11.bmp");
    //  //imwrite("wohhu", image);
    //  if (!image.data)
    //  {
    //      printf("duqucuowu");
    //  }
    int n = image.channels();

    imshow("origin", image);
    //CvtColor(image, gray, CV_RGB2GRAY);
    cvtColor(image, gray, CV_RGB2GRAY);
    //cvtColor(image, gray, CV_BGR2BGRA);
    imshow("origin1", gray);
    blur(gray, edge, Size(3, 3));   //模糊去噪  
    threshold(edge, edge, 200, 255, THRESH_BINARY);   //二值化处理  

    /*寻找轮廓*/
    findContours(edge, contours,
        CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
    int a = 22;
     itr = contours.begin();     //使用迭代器去除噪声轮廓  
    while (itr != contours.end())
    {
        area = contourArea(*itr);
        if ((area < minarea)&&area>0)
        {
            itr = contours.erase(itr);  //itr一旦erase,需要重新赋值  
        }
        else
        {
            itr++;
        }
        if (area > maxarea)
        {
            maxarea = area;
        }
    }
    dst = Mat::zeros(image.rows, image.cols, CV_8UC3);

    /*绘制连通区域轮廓,计算质心坐标*/
    Point2d center;
 itr = contours.begin();
    while (itr != contours.end())
    {
        area = contourArea(*itr);
        con.push_back(*itr);
        if (area == maxarea)
            drawContours(dst, con, -1, Scalar(0, 0, 255), 2);  //最大面积红色绘制  
        else
            drawContours(dst, con, -1, Scalar(255, 0, 0), 2);   //其它面积蓝色绘制  
        con.pop_back();

        //计算质心  
        mom = moments(*itr);
        center.x = (int)(mom.m10 / mom.m00);
        center.y = (int)(mom.m01 / mom.m00);
        centers.push_back(center);

        itr++;
    }
    imshow("origin", image);
    imshow("connected_region", dst);
    waitKey(0);

    /*漫水填充连通区域*/
    Point2d seed;
    int new_scalar = 0;
    int loDiff = 8, upDiff = 8;
    int connectivity = 4;

    itrc = centers.begin();
    while (itrc != centers.end())
    {
        seed = *itrc;
        floodFill(image, seed, Scalar::all(new_scalar), NULL,
            Scalar::all(loDiff), Scalar::all(upDiff), connectivity);
        itrc++;
    }

    waitKey(0);
    return 0;
}

你可能感兴趣的:(随记)