title: Python - Find center of object in an image
body: <p>I have an image file that's has a white background with a non-white object.
  I want to find the center of the object using python (Pillow).</p>
  
  <p>I have found a similar question in c++ but no acceptable answer - <a href="https://stackoverflow.com/questions/12394153/how-can-i-find-center-of-object">How can I find center of object?</a></p>
  
  <p>Similar question, but with broken links in answer - <a href="https://stackoverflow.com/questions/1203135/what-is-the-fastest-way-to-find-the-center-of-an-irregularly-shaped-polygon">What is the fastest way to find the center of an irregularly shaped polygon? (broken links in answer)</a></p>
  
  <p>I also read this page but it doesn't give me a useful recipe - <a href="https://en.wikipedia.org/wiki/Smallest-circle_problem" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Smallest-circle_problem</a></p>
  
  <p>Here's an example image: <a href="https://image.freepik.com/free-icon/moon-phase-black-crescent-shape_318-69954.png" rel="nofollow noreferrer"><img src="https://image.freepik.com/free-icon/moon-phase-black-crescent-shape_318-69954.png" alt="Moon"></a></p>
  
  <p>Edit:
  The current solution I'm using is this:</p>
  
  <pre><code>def find_center(image_file):
      img = Image.open(image_file)
      img_mtx = img.load()
      top = bottom = 0
      first_row = True
      # First we find the top and bottom border of the object
      for row in range(img.size[0]):
          for col in range(img.size[1]):
              if img_mtx[row, col][0:3] != (255, 255, 255):
                  bottom = row
                  if first_row:
                      top = row
                      first_row = False
      middle_row = (top + bottom) / 2  # Calculate the middle row of the object
  
      left = right = 0
      first_col = True
      # Scan through the middle row and find the left and right border
      for col in range(img.size[1]):
          if img_mtx[middle_row, col][0:3] != (255, 255, 255):
              left = col
              if first_col:
                  right = col
                  first_col = False
      middle_col = (left + right) / 2  # Calculate the middle col of the object
  
      return (middle_row, middle_col)
  </code></pre>