Masoud Rahimi Masoud Rahimi - 3 months ago 48
C++ Question

OpenCV C++ error in Mat:at

I'm new to OpenCV and C++. I am going to do a real time image processing with importing a frame by webcam and finding value of each pixel in it.
The following code works fine in my code,whenever I press a key it breaks from the loop and find the first black pixel in image. but If I remove the If statement for finding the first value of pixel in a endless loop it give me this error:


OpenCV Error: Assertion failed ((unsigned)i0 < (unsigned)size.p[0]) in cv::Mat::at, file c:\opencv\build\include\opencv2\core\mat.inl.hpp, line 917>


Here is some part of my code:

#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;
}


I would appreciate if someone help me about getting rid of this problem.
Thanks.

Answer

I solved the problem. My problem was in declaring the "src" matrix. I used CV_8UC1 then I replaced it with CV_8Uand problem solved.

Comments