简体   繁体   中英

Opencv 2 Mat- Error on runtime

I am starting with the basics of image processing and I am trying to convert a RGB image into grey scale using averaging.

My code is

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

#include<iostream>

using namespace cv;

int main()
{

    Mat image = imread("a.jpg");
    namedWindow("Original ");
    namedWindow("Grey");
    imshow("Original", image);  
    Mat grey;
    std::cout << "hello\n";
    for (int i = 0; i < image.rows; i++)
    {
        for (int j = 0; j < image.cols; j++)
        {
            grey.at<Vec3b>(i, j) = (image.at<Vec3b>(i, j)[0] + image.at<Vec3b>(i, j)[1] + image.at<Vec3b>(i, j)[2]);
        }
    }
    imshow("Grey", grey);
    return 0;   

}`

I think there is some problem with the Mat Grey , while accessing the element inside the for loop.

You need to initialize your grey ,

Mat grey(image.rows, image.cols, CV_8UC1);

And then, during processing,

    for (int j = 0; j < image.cols; j++)
    {
        grey.at<Vec3b>(i, j) = ((image.at<Vec3b>(i, j)[0] + image.at<Vec3b>(i, j)[1] + image.at<Vec3b>(i, j)[2]))/3;
    }

The /3 will give you the true grayscale value.

HTH

Of course, You have not initialized it, so it is empty, you cannot access the elements.

Mat grey = Mat::zeros(image.rows, image.cols, CV_8UC1); Should fix it.

Try using an if statement before accessing the elements of a Mat :

if (grey.empty())
{
  std::cout << "Empty Mat!\n";
  return -1;
}

Another thing is that adding the image channels are not the true grayacale, see this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM