# how can i determine the average tone of a given area in a grayscale image using opencv?

I’m not 100% certain what you are actually trying to do here, but I think you want to determine the tone of the background and subtract that or do something based on that to identify where your particles are. Without investing too much effort in case I am completely wrong, here is an approach that you/we could adapt to OpenCV if you like it.

Divide the image into a 10×10 regular grid. Calculate the variance, or standard deviation within each of the resulting 100 rectangles. Choose the one with the lowest variance – since it is the most constant one and least likely to have any particles in it – and then get that rectangle’s mean and use it as your image mean.

So, I did that with ImageMagick just in the Terminal. Here I am using a 5×5 grid rather than 10×10 to make the output smaller:

``````magick image.png -crop 5x5@ -format "%[standard-deviation] %[mean] %X %Y\n" info: | sort -n
``````

Output

``````835.2 49706.8 +410 +613
835.915 50146.3 +614 +153
845.005 49458 +819 +613
850.8 49997.2 +410 +460
852.937 50198 +614 +306
854.049 49577.4 +205 +460
857.193 50051.1 +614 +460
858.613 49752.5 +614 +613
859.179 49557.4 +819 +460
870.186 49298.2 +819 +0
872.404 48692.2 +205 +0
877.883 49439.4 +205 +613
878.972 49458.6 +205 +306
880.427 49391.9 +410 +0
882.476 47767.1 +0 +0
887.067 49180.4 +205 +153
897.929 48872.3 +0 +613
921.144 49753.9 +819 +153
932.777 48344.7 +0 +153
956.651 48550.5 +0 +306
987.255 48661.6 +0 +460
988.145 49776.3 +819 +306
1005.76 49909 +410 +153
1009.17 49685.2 +614 +0
1272.57 50062.4 +410 +306
``````

So, there are 25 lines – one line for each rectangle in the 5×5 grid. The first field on each line is the standard deviation in that rectangle, the second is the mean, the third is the x-offset of the top-left corner of the rectangle and the fourth is the y-offset of the top-left corner of the rectangle.

As I sorted by the standard deviation, the first line is the rectangle with the smallest variance, and its average grey value is 49706 on a scale of 0..65535. i.e. 193 on a scale of 0..255. That rectangle has its top-left corner at position [410,613]

You may be interested in “Local Area Thresholding”, see here. For example, on your image, you could highlight pixels that are 6% darker than their surrounding 100×100 area like this:

``````magick image.png -negate -lat 100x100+6%  result.png
`````` 