Search code examples
imageapiobjectcoordinatesanalysis

What's the easiest way to find the coordinates of an object in a image?


Imagine having an image of circles of different colors on a background of one color. What would be the easiest way to find the coordinates of the circles' centers (of course programmatically)?


Solution

  • I felt like doing it in Python with OpenCV as well, using the same starting image as my other answer.

    enter image description here

    The code looks like this:

    #!/usr/bin/env python3
    
    import numpy as np
    import cv2
    
    # Load image
    im = cv2.imread('start.png')
    
    # Convert to grayscale and threshold
    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(imgray,1,255,0)
    
    # Find contours, draw on image and save
    im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(im, contours, -1, (0,255,0), 3)
    cv2.imwrite('result.png',im)
    
    # Show user what we found
    for cnt in contours:
       (x,y),radius = cv2.minEnclosingCircle(cnt)
       center = (int(x),int(y))
       radius = int(radius)
       print('Contour: centre {},{}, radius {}'.format(x,y,radius))
    

    That gives this on the Terminal:

    Contour: centre 400.0,200.0, radius 10
    Contour: centre 500.0,200.0, radius 80
    Contour: centre 200.0,150.0, radius 90
    Contour: centre 50.0,50.0, radius 40
    

    And this as the result image:

    enter image description here