I’ve got a 640×480 binary image (0s and 255s). There is a single white blob in the image (nearly circular) and I want to find the centroid of the blob (it’s always convex). Essentially, what we’re dealing with is a 2D boolean matrix. I’d like the runtime to be linear or better if possible – is this possible?
Two lines of thought so far:
- Make use of the
numpy.where()function - Sum the values in each column and row, then find where the max value is based on those numbers… but is there a quick and efficient way to do this? This might just be a case of me being relatively new to python.
This code will find the centroid of any shaped image. It will find it exactly for
rez = 1. Increasingrez, increases the grid spacing, so can massively increase the speed of the search, at the obvious cost of the accuracy. If the size of the blob is known within bounds you could chain a lowrezsearch, with a highrezsearch, thus finding the answer quickly and priceselyfor example, with the below image:
Timing with
timeitthe first option (which is linear time,O(n)) has a run time of1.7s, and the second0.005s.You can’t do better than
O(n)to find an exact answer, unless you have some constraints on size and shape. But, you can sacrifice accuracy for speed. The above code isO(n/(rez ** 2)), which can be a massive improvement. The accuracy of reported results is:± rez / 2, in each dimension.Update:
sega_saiwrote a nice piece ofnumpycode (see post below) to find the centroid. I’ve modified it to take advantage of grid spacing, by using slicing. It operates in the same fashion as above:Here are graphed
timeitresults for these two functions over a span ofrezvalues:Its a log graph, so it really illustrates the advantage of combining the two approaches.
This is the image I used for the tests: