循环中运行时向量错误

时间:2013-08-03 17:30:02

标签: c++ visual-c++ opencv image-processing computer-vision

我的程序给出了向量迭代的运行时错误,下面是我的代码

for (i = 0; i != num_img; ++i)
{
    tmp_img = imread( files[i], 0 ); // load in grayscale.
    resize( tmp_img, tmp_dst, tmp_dst.size() );
    Mat row_img = tmp_dst.reshape( 1, 1 ); // get a one line image.
    row_img.convertTo( training_mat.row(i), CV_32FC1 );
    labels.at< float >(count, 0) = (count<nb_cars)?1:-1; // 1 for car, -1 otherwise*/
}

当我逐行检查时,它会向我显示循环中tmp_img的错误 这是错误 enter image description here 它的某个时候 enter image description here

3 个答案:

答案 0 :(得分:1)

最有可能的情况是您在此处访问超出范围的files向量:

for(int i = 0 ;  i < num_img ; i++ )
{
   tmp_img = imread( files[i], 0 ); // i could be larger than files.size()

您应该确保不要访问超出范围的向量。使用std::vector::size()方法。您可以检查num_img是否小于或等于files.size(),或完全删除num_img,然后循环遍历向量的内容。

编辑访问超出范围的向量是一个错误,并导致未定义的行为。如果你的程序这样做,那么它是不正确的,必须修复。

答案 1 :(得分:0)

请勿使用operator []
.at()让你好多了 因为它的格式i在范围内,如果不是,则会抛出out_of_range

string YourImagesDirectory="D:\\pics\\";
vector<string> files=listFilesInDirectory(YourImagesDirectory+"*.jpg");
for(size_t i = 0 ;  i < num_img ; i++ )
{
    try
    {
        tmp_img = imread( files.at(i), 0 );
    }
    catch(const std::out_of_range& e)
    {
         std::cerr << "num_img is bigger than files.size()!" << std::endl;
         std::cerr << "Exception caught! (out_of_range): " << e.what() << std::endl;
         break;
    }
    resize( tmp_img, tmp_dst, tmp_dst.size() );
    Mat row_img = tmp_dst.reshape( 1, 1 );
    row_img.convertTo( training_mat.row(i), CV_32FC1 );
    labels.at< float >(i, 0) = (i<nb_cars)?1:-1;
}

答案 2 :(得分:0)

尝试使用迭代器。它们可以帮助您保持范围;

int count = 0;
vector<string>::const_iterator i;
for (i = files.begin(); i != files.end(); ++i){
{
    tmp_img = imread( *i, 0 ); // load in grayscale.
    resize( tmp_img, tmp_dst, tmp_dst.size() );
    Mat row_img = tmp_dst.reshape( 1, 1 ); // get a one line image.
    // copy line and convert to float
    row_img.convertTo( training_mat.row(count), CV_32FC1 );
    labels.at< float >(count, 0) = (count<nb_cars)?1:-1; // 1 for car, -1 otherwise*/
    ++count;
}
相关问题