计算二值图像的重心(openCV Python)

2024-09-28 01:28:31 发布

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

我学习机械工程,这是我必须完成的第一个编程任务之一,因此我的编码经验(尤其是python和OpenCV)在我开始这项工作时几乎为零

我们得到了一张图片,应该写一个程序来计算形状的重心

这是我想出的代码

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('C:/Amoebe/Amoebebesser.png',0)
img = cv2.medianBlur(img,5)
ret,th1 = cv2.threshold(img,100,255,cv2.THRESH_BINARY)
plt.imshow(th1, cmap = 'gray', interpolation = 'none')
plt.show()

momentx = 0
momenty = 0
count = 0

for i in range(th1.shape[0]):
    for j in range(th1.shape[1]):
        if th1[i, j] >= 255:
            momentx = momentx + j
            momenty = momenty + i
            count = count + 1

centx = int(momentx / count)
centy = int(momenty / count)
print(centx)
print(centy)
cv2.circle(th1, (centy, centx), 1, (0, 0, 255), 2)
cv2.imshow('image', th1)
k = cv2.waitKey(0)
if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
    cv2.imwrite('centerofmasstest.png', th1)
    cv2.destroyAllWindows()

从我所读到的内容来看,有很多优化可以使用numpy来完成,但我不知道如何去做。另外,我不确定我是否真的得到了重心,或者我的方法中是否有错误

提前非常感谢您抽出时间向我致意


Tags: importnumpyimgforpngascountplt
2条回答

我们可以使用^{}np.average轻松地完成这项工作

# Find indices where we have mass
mass_x, mass_y = np.where(th1 >= 255)
# mass_x and mass_y are the list of x indices and y indices of mass pixels

cent_x = np.average(mass_x)
cent_y = np.average(mass_y)

编辑:Oneliner
center = [ np.average(indices) for indices in np.where(th1 >= 255) ]

您的代码看起来是正确的。我可能会关闭int(...)以获得亚像素分辨率质心值。坐标(0.0,0.0)将是左上角像素的中心

除了numpy解决方案外,还有^{},可以直接在轮廓和遮罩图像上运行,它提供了various moment values(m00,m10,m01,…)可以用来计算质心(m10/m00,m01/m00)

m00是计数,m10是动量x,m01是动量

相关问题 更多 >

    热门问题