Reputation: 534
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.
Upvotes: 1
Views: 496
Reputation: 2291
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.
Upvotes: 1
Reputation: 1198
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
Upvotes: 2