[Solved] Opencv Error: Error: Assertion failed (data) in cv::Mat::at, file … mat.inl.hpp, line 897(Accessed pixels of non-existent matrix)

Opencv4 error

This is the source code:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main(int argc, const char* argv[]) {

	Mat src, dst;
	src = imread("./test.jpg");
	//if (src.empty()) {
	if (!src.data){
		printf("could not load image...\n");
		return -1;
	}
	//namedWindow("input img");
	//imshow("input img", src);

	//Three for loops, performing operations g_dstImage(i,j) =a*g_srcImage(i,j) + b
	for (int y = 0; y < src.rows; y++)
	{
		for (int x = 0; x < src.cols; x++)
		{
			for (int c = 0; c < 3; c++)
			{
				//g_dstImage.at<Vec3b>(y, x)[c] = saturate_cast<uchar>((g_nContrastValue*0.01)*(g_srcImage.at<Vec3b>(y, x)[c]) + g_nBrightValue);
				dst.at<Vec3b>(y, x)[c] = src.at<Vec3b>(y, x)[c];
			}
		}
	}


	namedWindow("output img");
	imshow("output img", dst);

	waitKey(0);
	return 0;
}

Vs compile run error:

reason

The nonexistent subscript of the access array (because we did not initialize the size and data type of mat array DST in the above code…)

Solution:

Add code: dst = Mat::zeros(src.size(), src.type());

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main(int argc, const char* argv[]) {

	Mat src, dst;
	src = imread("./test.jpg");
	//if (src.empty()) {
	if (!src.data){
		printf("could not load image...\n");
		return -1;
	}
	namedWindow("input img");
	imshow("input img", src);

	dst = Mat::zeros(src.size(), src.type());	

	//Three for loops, performing operations g_dstImage(i,j) =a*g_srcImage(i,j) + b
	for (int y = 0; y < src.rows; y++)
	{
		for (int x = 0; x < src.cols; x++)
		{
			for (int c = 0; c < 3; c++)
			{
				//g_dstImage.at<Vec3b>(y, x)[c] = saturate_cast<uchar>((g_nContrastValue*0.01)*(g_srcImage.at<Vec3b>(y, x)[c]) + g_nBrightValue);
				dst.at<Vec3b>(y, x)[c] = 255 - src.at<Vec3b>(y, x)[c];
			}
		}
	}


	namedWindow("output img");
	imshow("output img", dst);

	waitKey(0);
	return 0;
}

Vs compilation run result:

Read More: