Search code examples
python-3.xnumpyopencv3.0centroid

Finding centroid of two(or more) contours


I have binary images like below. I want to get cetroid of white regions.(not centroids of each contours) This image has two seperated contours

binary image]

    _, contour, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    total_contour = contour[0]
    for ctr in contour[1:]:
            total_contour = np.concatenate((total_contour, ctr), axis =0)

    mmt = cv2.moments(total_contour)
    self.cy = int(mmt['m10']/mmt['m00']) 
    self.cx = int(mmt['m01']/mmt['m00']) 

So I just simply added np.array of contours, and used moments in openCV. It looks working well... but I'm not sure that self.cx and self.cy are really cetroid of white regoins.

Am I doing right? If not, what would be better method?


Solution

  • If you're unsure about the result you're getting from openCV, you can always just calculate the centroid yourself. It's quite simple, here's how:

    centroid = [nz.mean() for nz in binary_image.nonzero()]
    

    If you want the centroid in the same x,y index format as you're getting from openCV, do this:

    import numpy as np
    centroid = np.array([nz.mean() for nz in binary_image.nonzero()][2::-1], dtype=int)
    

    I ran the above line of code on the image you posted in your question, and here's what I got:

    [133  44]
    

    If it makes you feel better, that does match the values that I get for cx and cy when I run the openCV snippet you posted. So I guess you were doing it right all along!