【发布时间】:2016-09-27 21:42:02
【问题描述】:
我有一个带有非白色对象的白色背景的图像文件。 我想使用 python (Pillow) 找到对象的中心。
我在 c++ 中发现了一个类似的问题,但没有可接受的答案 - How can I find center of object?
类似的问题,但答案中的链接断开 - What is the fastest way to find the center of an irregularly shaped polygon? (broken links in answer)
我也阅读了这个页面,但它没有给我一个有用的食谱 - https://en.wikipedia.org/wiki/Smallest-circle_problem
编辑: 我正在使用的当前解决方案是这样的:
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)
【问题讨论】:
-
@user20160 不幸的是,提到的答案再次破坏了链接 - 没有可用的代码