1

I have a matrix of 630 values (values range from 0-35)...

I want to find the most frequently occurring value in this matrix. So how do I write a histogram for this? Also is there any other way that I can find the most frequently occurring value (I don't want to use counters as i will need 36 counters and My code would become very inefficient)

..Thanks!

2 Answers 2

3

You can use calcHist with a Mat of size 1xN, where N is 630 in your case.

I don't understand your argument against counters. To build the histogram, you must use counters anyway. There are ways to make counting very efficient.

OR

Assuming your image is a cv::Mat variable im with size 1x630 and type CV_8UC1, try:

std::vector<int> counts(36, 0);
for (int c = 0; c < 630; c++)
    counts.at(im.at<unsigned char>(1, c)) += 1;
std::cout << "Most frequently occuring value: " << std::max_element(counts);

This uses counting, but will not take more than 0.1ms on an average PC.

Sign up to request clarification or add additional context in comments.

2 Comments

But I would have to use counter1++,counter2++ and so on ....counter35++...which would be very inefficient??
That's pretty much what a histogram is. When you want to refer to set of values like counter1, counter2, etc, we call that an array, so we get counter[1], counter[2], etc. But now since they're stored in an array, we don't need to refer to them with if statements, we can just use our pixel value directly as the array index. counter[pixelValue]++. Voila, a histogram.
1

Why not do it manually?

Mat myimage(cvSize(1,638), CV_8U);
randn(myimage, Scalar::all(128), Scalar::all(20)); //Random fill
vector<int> histogram(256);
for (int i=0;i<638;i++)
    histogram[(int)myimage.at<uchar>(i,0)]++;

3 Comments

@William...Lemme just try this out
Im not so clear about your code...is votes the histogram that is initially generated..or do i use it here AFTER i have already generated a histogram?
ok...the naming is clear..Im assuming ill be initializing the vector as :vector<int>histogram(36) as Im using values in the range 0-35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.