寻找对象中心:在目标对象之外显示错误的坐标

Finding object center: showing wrong coordinate outside of the target object

我按照 this link 中的代码找到了我的灰度图像的对象中心,

def find_center(im):
    immat = im
    (X, Y) = [im.shape[0],im.shape[1]]
    m = np.zeros((X, Y))

    for x in range(X):
        for y in range(Y):
            m[x, y] = immat[(x, y)] != 0
    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))
    return [cx,cy]

xy1=find_center(img)  #img is a binary image, object has value==1 and back ground value of 0
print xy1
plt.imshow(img)
plt.annotate('center', xy1, xycoords='data',
             xytext=(0.5, 0.5), textcoords='figure fraction',
             arrowprops=dict(arrowstyle="->"))
plt.show()

但是,我没有得到正确的答案(中心不在对象内部),下图显示了输出:

我做错了什么?

我认为函数 find_center 正在正确计算中心坐标。不过,有一种更优雅、更有效的方法来执行此计算(请参阅下面的代码片段)。

问题是您正在传递 xy1,即 [cx, cy]plt.annotate,但您需要传递 [cy, cx]。如果您将代码更改为 xy1 = find_center(img)[::-1],问题应该得到解决。

试试这个代码:

import numpy as np
from skimage import io
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

triskele = io.imread('https://i.stack.imgur.com/fczjh.png')
img = triskele > 0

[cx, cy] = np.transpose(np.nonzero(img)).mean(axis=0)

fig, ax = plt.subplots(1)
ax.imshow(img, cmap=plt.cm.gray)
ax.axis('off')
ax.add_patch(Circle((cy, cx), radius=12, color='red'))
plt.show(fig)