Tiffado
Tiffado

Reputation: 452

Estimate average brightness of a grayscale picture with opencv

I have a grayscale picture, and I would to transform it to black and white only. But for that, I need to calculate the right threshold, and I would like that threshold to be equal to the average brightness of the picture.

So, I was wondering how I could calculate that threshold with OpenCV. Is there a method existing in the framework to do that easily ?

I wanted to add every value of brightness (between 0 and 255) for every pixel, then divide the sum by the number of pixel itself, but the method I found to access those datas is really slow (.at(i,j)[k] for a rgb picture). But my picture is in grayscale, and I would like it to be quite fast, so it can be run on an iPhone.

Upvotes: 1

Views: 18847

Answers (2)

Boyko Perfanov
Boyko Perfanov

Reputation: 3047

You can use a Monte Carlo algorithm, sampling random points instead of all image points until you have covered 1% of the image. The result should be very similar to the actual value.

Upvotes: 0

ypnos
ypnos

Reputation: 52337

To calculate these statistics, use cv::sum(), or even better, cv::mean().

However, OpenCV already has a thresholding function that does everything you want to do for you: cv::adaptiveThreshold()

Also you should check out Otsu's method, see cv::threshold() with THRESH_OTSU option.

Upvotes: 6

Related Questions