1

I want to do a feature extraction from an image to a 3D histogram in the RGB colorspace. I have the following python code which I want to do it under c++:

hist = cv2.calcHist([image], [0, 1, 2], None, self.bins, [0, 256, 0, 256, 0, 256])        
hist = cv2.normalize(hist)
return hist.flatten()

I did something like this:

float range[] = { 0, 255 } ;   
const float* histRange = { range };
int channels[] = {0};
cv::calcHist( &image, 1, channels, cv::Mat(), r_hist, 1, &sizeVector[0], &histRange);
channels[0] = 1;
cv::calcHist( &image, 1, channels, cv::Mat(), g_hist, 1, &sizeVector[0], &histRange);
channels[0] = 2;
cv::calcHist( &image, 1, channels, cv::Mat(), b_hist, 1, &sizeVector[0], &histRange);

But then I found that they are not the same since in python the histogram is counting in 3D-based, how to convert the code to c++?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
sflee
  • 1,659
  • 5
  • 32
  • 63

1 Answers1

1

Here is the code example from OpenCv documentation:

http://docs.opencv.org/doc/tutorials/imgproc/histograms/histogram_calculation/histogram_calculation.html#code

The approach here is to split the three channels first and then calculate the histogram for each channel.

For a 3D histogram, refer to this answer:

How to access 3D Histogram values in C++ using OpenCV?

Community
  • 1
  • 1
Totoro
  • 3,398
  • 1
  • 24
  • 39
  • 1
    It seems that this code cannot do what I want. In the python, every point will be counted once. But if I split it into three plants and count them one by one, then every point will be counted three times. – sflee Jun 09 '15 at 02:05
  • You can normalise histograms, so a point counted three times is actually fine. Since every pixel must have all three values, it should not cause an error. – Totoro Jun 09 '15 at 02:08
  • Sorry, I don't understand what you mean~"~ I mean if I have a point that belongs to Bin_{r}(1) and Bin_{g}(4) and Bin_{b}(6). By the python code, I will have a 3D histogram that count this point into a bin [1, 4, 6], for an example. But if I do it in c++ by splitting method, how can I merge the result back? – sflee Jun 09 '15 at 02:15
  • 1
    Sorry, I finally got it. If you need a 3D histogram, you cannot get it using this method. But you can write your own code to do that. I think the code here tries that. http://stackoverflow.com/questions/26421806/how-to-access-3d-histogram-values-in-c-using-opencv. Updated the answer with this, so that it is useful to others as well. – Totoro Jun 09 '15 at 02:32