代码之家  ›  专栏  ›  技术社区  ›  Leo

在图像中查找重心

  •  5
  • Leo  · 技术社区  · 6 年前

    这是我的照片: enter image description here

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

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

    3 回复  |  直到 3 年前
        1
  •  20
  •   Juan    6 年前

    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()
    

    这给了我以下输出:

    eye center of mass

    你会注意到有一些你可能不想要的前景,比如在图片的右下角。这完全是另一个答案,但你可以看看 scipy.ndimage.label , skimage.morphology.remove_small_objects ,更普遍的是 skimage.segmentation .

        2
  •  2
  •   ldavid    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
  •  0
  •   Moia    6 年前

    你需要知道 Image Moments .

    Here 有一个关于如何将其与opencv和python结合使用的教程