【问题标题】:Finding the center of mass in an image在图像中找到质心
【发布时间】:2022-02-23 01:36:45
【问题描述】:

这是我的图片:

我想在这张图片中找到质心。我可以通过绘制两条垂直线来找到质心的大致位置,如下图所示:

我想使用 python 中的图像处理工具找到它。我对 python 的图像处理库(scikit-image)有一点经验,但是我不确定这个库是否可以帮助找到我图像中的质心。 我想知道是否有人可以帮助我做到这一点。如果可以使用 python 中的任何其他库在我的图像中找到质心,我会很高兴。 提前感谢您的帮助!

【问题讨论】:

  • Stack Overflow 不是一个可以提交代码请求的网站。
  • 索取代码?!请仔细阅读我的问题,并让我知道我在哪里请求代码。我只是寻求帮助。
  • 听起来你在找skimage.measure.moments (scikit-image.org/docs/dev/api/skimage.measure.html)
  • 我看了看,但我没看对。是否可以提供一个非常简单的示例,例如在图像中查找正方形或圆形的输入,以便我可以学习如何在我的图像中实现它?

标签: python image-processing scikit-image


【解决方案1】:

skimage.measure.regionprops 会做你想做的事。这是一个例子:

import imageio as iio
from skimage import filters
from skimage.color import rgb2gray  # only needed for incorrectly saved images
from skimage.measure import regionprops

image = rgb2gray(iio.imread('eyeball.png'))
threshold_value = filters.threshold_otsu(image)
labeled_foreground = (image > threshold_value).astype(int)
properties = regionprops(labeled_foreground, image)
center_of_mass = properties[0].centroid
weighted_center_of_mass = properties[0].weighted_centroid

print(center_of_mass)

在我的机器上并使用您的示例图像,我得到(228.48663375508113, 200.85290046969845)

我们可以拍一张漂亮的照片:

import matplotlib.pyplot as plt
from skimage.color import label2rgb

colorized = label2rgb(labeled_foreground, image, colors=['black', 'red'], alpha=0.1)
fig, ax = plt.subplots()
ax.imshow(colorized)
# Note the inverted coordinates because plt uses (x, y) while NumPy uses (row, column)
ax.scatter(center_of_mass[1], center_of_mass[0], s=160, c='C0', marker='+')
plt.show()

这给了我这个输出:

您会注意到,您可能不希望其中有一些前景,例如图片的右下角。这完全是另一个答案,但您可以查看scipy.ndimage.labelskimage.morphology.remove_small_objects,以及更一般的skimage.segmentation

【讨论】:

    【解决方案2】:

    您可以使用scipy.ndimage.center_of_mass 函数找到物体的质心。

    例如,使用这个问题的图片:

    wget https://i.stack.imgur.com/ffDLD.jpg
    
    import matplotlib.image as mpimg
    import scipy.ndimage as ndi
    
    img = mpimg.imread('ffDLD.jpg')
    img = img.mean(axis=-1).astype('int')  # in grayscale
    
    cy, cx = ndi.center_of_mass(img)
    
    print(cy, cx)
    
    228.75223713169711 197.40991592129836
    

    【讨论】:

    • 考虑包含您使用的图像并包含打印语句的输出。
    【解决方案3】:

    您需要了解Image Moments

    Here 有一个如何与opencv和python一起使用的教程

    【讨论】:

    • 请在您的答案中添加一些信息。一旦链接失效,仅提供链接将使您的答案无用。
    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 2019-09-24
    • 2017-10-07
    • 1970-01-01
    • 2013-01-05
    • 2018-04-01
    • 1970-01-01
    • 2013-05-13
    相关资源
    最近更新 更多