OpenCV rgb value for cv :: Point in cv :: Mat

I have already covered various issues that StackOverflow already has, but nothing seems to help. What I want to do is pretty simple: I have cv::Point and I need to get the RGB value for the pixel at that point in cv::Mat so that I can compare it with the saved RGB value.

Now it should be very simple, but I tried 1001 different ways and it just does not work for me.

Someone please help me out of my misery!

edit: both answers below work! I am new to C ++ and don't know that unsigned char output via cout gives a question! printf offcourse gives the correct value !!

+4
source share
2 answers

It is very simple. However, the OpenCV documentation is good for hiding simple answers.

Here is a sample code:

 cv::Mat3b image = imread(filename); cv::Point point(23, 42); cv::Vec3b template; template[0] = 128; template[1] = 12; template[2] = 64; const cv::Vec3b& bgr = image(point); if (bgr[0] == template[0] && bgr[1] == template[1] && bgr[2] == template[2]) std::cout << "Colors match!" << std::endl; 

There are likely better ways to deal with cv :: Vec, but I forgot. See also OpenCV Cheat Sheet .

+9
source

It depends on the type of image / mat. If the image is the usual 1 byte for each rgb per pixel, then this is one way to access it. This is quite effective, but not the safest way:

 // The RGB values are stored in reverse order (i don't know why) struct RGB { unsigned char b, g, r; }; // Assumes 1 byte for r,g,b RGB& GetRGB(cv::Mat &mat, cv::Point p) { assert((mat.step/mat.cols) == sizeof(RGB)); RGB *data = (RGB*)mat.data; data += py * mat.cols + px; return *data; } 

If Mat has a different type, you just need to change the RGB structure to fit what you need.

Try changing the type of image you are reading to a regular RGB image with this code:

 Mat in, out; cvtColor(in, out, CV_8UC3); 
0
source

Source: https://habr.com/ru/post/1336315/


All Articles