Python - Encuentra el centro del objeto en una imagen
Tengo un archivo de imagen que tiene un fondo blanco con un objeto no blanco. Quiero encontrar el centro del objeto usando python (Pillow).
He encontrado una pregunta similar en c ++ pero no hay una respuesta aceptable:¿Cómo puedo encontrar el centro del objeto?
Pregunta similar, pero con enlaces rotos en respuesta:¿Cuál es la forma más rápida de encontrar el centro de un polígono de forma irregular? (enlaces rotos en respuesta)
También leí esta página pero no me da una receta útil.https://en.wikipedia.org/wiki/Smallest-circle_problem
Aquí hay una imagen de ejemplo:
Editar: La solución actual que estoy usando es esta:
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)