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

2024-09-29 17:45:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我按照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()

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

enter image description here

我做错什么了


Tags: 对象inimgfornprangepltfind
1条回答
网友
1楼 · 发布于 2024-09-29 17:45:36

我认为函数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)

Center position

相关问题 更多 >

    热门问题