我按照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]
,问题应该得到解决请尝试以下代码:
相关问题 更多 >
编程相关推荐