python - 计算二值图像的质心 (openCV Python)

标签 python numpy opencv

我学习机械工程,这是我必须执行的第一个编程任务之一,因此当我开始此操作时,我的编码经验(尤其是 Python 和 open cv 方面)几乎为零。

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

这是我想出的代码,

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 完成很多优化,但我不知道如何做到这一点。另外,我不确定我是否真的得到了质心或者我的方法是否有错误。

提前非常感谢您的宝贵时间和最诚挚的问候。

最佳答案

我们可以使用np.wherenp.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) 用于 np.where(th1 >= 255) 中的索引 ]

关于python - 计算二值图像的质心 (openCV Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65304623/

相关文章:

python - 执行 K 均值聚类时出现的问题

python - 从骨灰盒中绘制的 Numpy

OpenCV 神经网络权重

python - IO错误: [Errno 21] Is a directory: '/tmp/speech_dataset/'

python - .backward() 之后 pytorch grad 为 None

python - 值错误: arrays must all be same length

python - 从源代码构建 OpenCV 3.4 - 未生成 CV2.so - Ubuntu16.04

Python如何根据子字符串过滤字符串

python - 基于数字从python列表中删除元素

c++ - MOG2 背景扣除参数