Python 查找对象中心:显示目标对象外部的错误坐标

Python 查找对象中心:显示目标对象外部的错误坐标,python,image,matplotlib,image-processing,scikit-image,Python,Image,Matplotlib,Image Processing,Scikit Image,我按照中的代码查找灰度图像的对象中心 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)) # m

我按照中的代码查找灰度图像的对象中心

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()
但是,我没有得到正确的答案(中心不在对象内部),下图显示了输出:


我做错了什么?

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

问题是您正在将
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)

如果图像旋转了180度,那么中心看起来是正确的。注意,
im.shape[0]
返回图像高度,而不是宽度,因此您可能想将其指定给
Y
,而不是
X
@101。它不会做任何更改。非常感谢您的帮助,这是非常有效的:)