python - 计算二值图像的质心(openCV Python)
问题描述
我学习机械工程,这是我必须做的第一个编程任务之一,所以当我开始这个时,我的编码经验,尤其是在 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.where
和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) ]
推荐阅读
- c++ - 尝试初始化结构的二维数组并引发读取访问冲突异常
- c# - .NET Core 3.1 BackgroundService - 使用 RabbitMQ 并使用 EntityFrameCore 插入
- php - 如何让我的网站在所有屏幕上看起来都一样?
- flutter - 如何将 FlexibleSpaceBar 移动到 SliverAppbar 滚动的中心
- javascript - 如何使用 Lodash 添加未定义的检查?
- android - 使字符串资源中的 formatArg 加粗 Andoid
- c++ - 使用 OOP 的算术运算
- vue.js - 如何在 VSCode 中为继承的 VueJS 组件的属性添加智能感知?
- python - Python requests 库每次都会创建新的连接
- python - Django 密码验证器:如果任何三个验证通过用户可以继续