Reputation: 2212
hi all i am trying to get the RGB for a pixel in an image using C++ openCV 2.4.5
but i get this error when i compile .
it loads the image will but the exception arise when i am trying to get the RGB for a pixel
can any one help me please ?
the following code loads an image and find the RGB for a pixel at index 25,4
my code is :
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
int x;
Mat input = imread("C:/red.jpg");
if (input.empty())
{
std::cout << "!!! Failed imread(): image not found" << std::endl;
cin>>x;
return 0;
// don't let the execution continue, else imshow() will crash.
}
imshow("input", input);
Vec3f pixel = input.at<Vec3f>(25, 40);
if( !pixel[0])
{
std::cout << "!!! Failed pixel(): image not found" << std::endl;
cin>>x;
return 0;
}
int b = pixel[0];
int g = pixel[1];
int r = pixel[2];
cout<<b;
cout <<" ";
cout<<r;
cout <<" ";
cout <<g;
cin>>b;
/*
// detect squares after filtering...
*/
return 0;
}
Upvotes: 0
Views: 1757
Reputation: 1
you should use :
Mat input = imread("C://red.jpg");
instead of :
Mat input = imread("C:/red.jpg");
Upvotes: 0
Reputation: 5978
You image is probably of type CV_8UC3, which means the value of a pixel is stored as 3-channel 8-bit uchar. In
Vec3f pixel = input.at<Vec3f>(25, 40);
you are trying to access pixel values as floats, since in OpenCV Vec3f
is defined as typedef Vec<float, 3> Vec3f;
. This causes your program to crush. Instead it should be:
Vec3b pixel = input.at<Vec3b>(25, 40);
In OpenCV Vec3b
is defined as typedef Vec<uchar, 3> Vec3b;
, which is what you want.
Here's the documentation for cv:: Vec data type.
EDIT You can output the pixel data simply with
cout << pixel << endl;
or like this:
printf("[%u, %u, %u]", pixel[0], pixel[1], pixel[2]);
or like this:
int b = static_cast<int>(pixel[0]);
int g = static_cast<int>(pixel[1]);
int r = static_cast<int>(pixel[2]);
cout<< "[" << b <<", " << g << ", " << r << "]" << endl;
Upvotes: 3