gpt4 book ai didi

Python - 在图像中查找对象的中心

转载 作者:太空狗 更新时间:2023-10-30 02:02:55 24 4
gpt4 key购买 nike

我有一个图像文件,它有一个白色背景和一个非白色对象。我想使用 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

这是一个示例图片:Moon

编辑:我正在使用的当前解决方案是:

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)

最佳答案

如果您将中心定义为 Center of Mass ,那么这并不困难,尽管 CoM 可能在您的形状之外。您可以将图像解释为 2D distribution , 你可以找到它的 expected value (CoM) 使用积分(求和)。

如果你有 numpy,那就很简单了。首先创建一个包含 1 的 numpy 数组,其中您的图像是非白色的,然后使其成为概率分布,将其除以图像的总数。

from PIL import Image
import numpy as np

im = Image.open('image.bmp')
immat = im.load()
(X, Y) = im.size
m = np.zeros((X, Y))

for x in range(X):
for y in range(Y):
m[x, y] = immat[(x, y)] != (255, 255, 255)
m = m / np.sum(np.sum(m))

从这一点开始,它变成了基本的概率论。您找到边际分布,然后计算预期值,就好像它是离散概率分布一样。

# marginal distributions
dx = np.sum(m, 1)
dy = np.sum(m, 0)

# expected values
cx = np.sum(dx * np.arange(X))
cy = np.sum(dy * np.arange(Y))

(cx, cy) 是您正在寻找的 CoM。

result CoM

备注:

  • 如果你没有 numpy,你仍然可以做到。这只是有点乏味,因为您必须通过循环/理解来进行求和。
  • 如果您想根据颜色分配“质量”,则可以轻松扩展此方法。您只需将 m[x, y] = immat[(x, y)] != (255, 255, 255) 更改为 m[x, y] = f(immat [(x, y)]) 其中 f 是任意(非负值)函数。
  • 如果你想避免双重循环,你可以使用 np.asarray(im),但要小心索引

没有循环:

m = np.sum(np.asarray(im), -1) < 255*3
m = m / np.sum(np.sum(m))

dx = np.sum(m, 0) # there is a 0 here instead of the 1
dy = np.sum(m, 1) # as np.asarray switches the axes, because
# in matrices the vertical axis is the main
# one, while in images the horizontal one is
# the first

关于Python - 在图像中查找对象的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com