矢量下标超出范围 - C ++ Vectors / OpenCV

时间:2017-07-12 03:54:06

标签: c++ opencv vector

我正在编写一个程序,找到蓝色矩形' 4个顶点并计算每个矩形的宽度和高度。 它适用于某些图像,但其他图像会显示"矢量下标超出范围" 我应该怎么解决它。

我的节目:

#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <D:\opencv\build\include\opencv2\highgui.hpp>
#include "D:\opencv\build\include\opencv2\imgcodecs.hpp"
#include "D:\opencv\build\include\opencv2\imgproc.hpp"
//#include "D:\opencv\build\include\opencv2\text.hpp"

using namespace cv;
using namespace std;
int main(int argc, const char** argv)
{
fstream file;
Mat src = imread("TNR4.jpg");
Mat hsv;
Mat dst;
Mat mask = Mat::zeros(src.rows, src.cols, CV_8U);
Mat b;
Rect roi;
Mat gray;

cvtColor(src, hsv, CV_BGR2HSV);
inRange(hsv, Scalar(110, 100, 120), Scalar(130, 255, 255), b);
mask = b;
src.copyTo(dst, mask);//dst=藍框圖
cvtColor(dst, gray, CV_RGB2GRAY);

Mat bin;
threshold(gray, bin, 100, 255, THRESH_BINARY);

vector<vector<Point>> contours;

findContours(bin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

file.open("GroundTruth.txt", ios::out);      //開啟檔案

try
{

    for (unsigned int i = 0; i < contours.size(); i++) {


        approxPolyDP(Mat(contours[i]), contours[i], 10, true);
        file << "第" << i + 1 << "個框框" << endl;
        file << "Point(x,y)=" << contours[i][0].x << "," << contours[i][0].y << endl;
        cout << i << endl;
        file << "寬: " << contours[i][3].x - contours[i][0].x << " 高: " << contours[i][1].y - contours[i][0].y << endl;
        file << endl;

        for (unsigned int j = 0; j < 4; j++) {
                circle(dst, contours[i][j], 3, Scalar(0, 0, 255), FILLED, LINE_AA);
        }
    }
}

catch (const std::exception&)
{

}
imwrite("bin.jpg", bin);
imwrite("result.jpg", dst);
//system("pause");
}

the src image

dst image and the txt file

src图像很大,这只是它的一小部分

0 个答案:

没有答案