opencvc++在Mat:at中的错误

OpenCV C++ error in Mat:at

本文关键字:错误 at Mat opencvc++      更新时间:2023-10-16

我是OpenCV和c++的新手。我要做一个实时的图像处理,通过网络摄像头导入一帧,并找到其中每个像素的值。下面的代码在我的代码中工作得很好,每当我按下一个键时,它就会跳出循环并找到图像中的第一个黑色像素。但是如果我删除If语句来查找无尽循环中pixel的第一个值它会给我这个错误:

OpenCV Error: Assertion failed ((unsigned)i0 <(unsigned)size.p[0]) in cv::Mat::at, file c:opencvbuildincludeopencv2core Mat .inl.hpp, line 917>

下面是我的部分代码:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <windows.h>
using namespace cv;
using namespace std;
/// Global variables
int maxRepeating(int* arr, int n, int k);
int main(int, char** argv)
{
    Mat frame, src1;
    Mat bgr_image;
    Mat dst(frame.size(), CV_8UC1, cv::Scalar(0));
    Mat src(frame.size(), CV_8UC1, cv::Scalar(0));
    /// Load an image
    VideoCapture cap(1); // open the default camera
    if (!cap.isOpened())  // check if we succeeded
        return -1;
    //  namedWindow("src", 1);
    cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
capturing:
    for (;;)
    {
        cap >> frame; // get a new frame from camera
        if (frame.empty()) return 0;
        cvtColor(frame, src1, CV_BGR2GRAY);
        imshow("src", src1);
        if (waitKey(30) >= 0) break;  //if I remove this line and put the following two lines I get the error
// waitKey(10);
// break;
    }   
    int operation = 4;
    double morph_size = 2;
    //preprocessing
    //...
    Mat element = getStructuringElement(MORPH_RECT, Size(2 * morph_size + 1, 2 * morph_size + 1), Point(-1, -1));
    /// Apply the specified morphology operation
    morphologyEx(src1, dst, operation, element);
    threshold(dst, src, 128, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
    int i = 0;
    int j = 0;
    int p = 0;
    int q = 0;
    int flag = 0;
    int cnt = 0;
    int cm = 0;
    int flagold = 10;
    int f0 = 1, f1 = 1, f2 = 1, f3 = 1, f4 = 1, f5 = 1, f6 = 1, f7 = 1;
    int chain[100000];
    std::fill(chain, chain + size(chain), 9);
    int val = 0;
    for (i = 0; i < src.rows; i++) {
        for (j = 0; j < src.cols; j++) {
            val = src.at<uchar>(i, j); //I think problem is with this line
            if (val == 0) {
                cout << "fist pixel found!";
                cout << "i=" << i << "j=" << j << endl;
                p = i;
                q = j;
                goto st;
            }
        }
    }
st:
//some stuff...
goto capturing;
}
如果有人帮我解决这个问题,我会很感激的。谢谢。

更有效和正确的方法是这样访问每个像素:

for(int i = 0; i < src.rows; ++i)
{
    const uchar* row = src.ptr<uchar>(i);
    for(int j = 0; j < src.cols; ++j)
    {
         if(row[j] == 0)
            ....
    }
}

我解决了这个问题。我的问题是在声明"src"矩阵。我使用CV_8UC1,然后我用CV_8U替换它,问题解决了。