OpenCV错误:在cv :: Mat :: at中断言失败((unsigned)i0 <(unsigned)size.p [0])

时间:2018-12-02 15:04:38

标签: c++ c opencv

我正在尝试在500x500白色背景图像上绘制点。

void Lab1() {

    float px[500];
    float py[500];
    float x, y;
    int nrPoints;
        //citire puncte din fisier
    FILE *pfile;
    pfile = fopen("points0.txt", "r");

        //punere in variabila
    fscanf(pfile, "%d", &nrPoints);

       //facem o imagine de 500/500 alba
    Mat whiteImg(500, 500, CV_8UC3);

    for (int i = 0; i < 500; i++) {
        for (int j = 0; j < 500; j++) {
            whiteImg.at<Vec3b>(i, j)[0] = 255; // b
            whiteImg.at<Vec3b>(i, j)[1] = 255; // g
            whiteImg.at<Vec3b>(i, j)[2] = 255; // r

        }
    }


      //punem punctele intr-un vector,pentru a le putea pozitiona ulterior in imaginea alba.

    for (int i = 0; i < nrPoints; i++) {
        fscanf(pfile, "%f%f", &x, &y);

        px[i] = x;
        py[i] = y;
        //afisam punctele
        printf("%f ", px[i]);
        printf("%f\n", py[i]);
    }

      //punem punctele pe imagine

    for (int i = 0; i < nrPoints; i++) {
        whiteImg.at<Vec3b>(px[i],py[i]) = 0;
    }

    imshow("img",whiteImg);
    fclose(pfile);
     //system("pause");
    waitKey();
}

问题出在这里:

whiteImg.at<Vec3b>(px[i],py[i]) = 0;

我无法避免此错误:

  

OpenCV错误:在cv :: Mat :: at文件c:\ users \ toder \ desktop \ anul4 \ srf \ laburi_srf \ opencvapplication中,声明失败((unsigned)i0 <(unsigned)size.p [0]) -vs2015_31_basic \ opencv \ include \ opencv2 \ core \ mat.inl.hpp,第917行

1 个答案:

答案 0 :(得分:3)

您将Mat声明为

Mat(500, 500, CV_8UC3); 

CV_8UC3 意味着它具有三个通道:一个用于红色,一个用于蓝色,一个用于绿色。您不能在具有三个通道(Vec3b)的Mat中设置0(整数)。考虑到要在图像的给定点上设置值为0,要绘制的点颜色为黑色。

您可以这样做:

whiteImg.at<Vec3b>(px[i],py[i]) = Vec3b(0,0,0);

或者,为了与您的代码风格一致:

whiteImg.at<Vec3b>(px[i],py[i])[0] = 0; //Blue Channel
whiteImg.at<Vec3b>(px[i],py[i])[1] = 0; //Green Channel
whiteImg.at<Vec3b>(px[i],py[i])[2] = 0; //Red Channel