python - 用opencv计算质心
问题描述
我有多个圆圈的图像,圆圈内有热点区域,高强度(高像素值)和冷点区域(低像素值)。我想用 Python 中的 OpenCV 计算每个圆的加权质心。我正在使用这段代码:
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# calculate moments for each contour
M = cv2.moments(c)
# calculate x,y coordinate of center
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
else:
cX, cY = 0, 0
好的,所以这段代码只是取二进制图像,提取所有圆并找到每个圆的轮廓。
问题是我需要找到 RGB/灰度图像(考虑像素强度)的加权质心,而不是二值图像。我怎样才能做到这一点?
谢谢!
解决方案
对@yapws87 答案的一些修复:
import numpy as np
import cv2
# create a meshgrid for coordinate calculation
r,c = np.shape(ori_img)
r_ = np.linspace(0,r,r+1)
c_ = np.linspace(0,c,c+1)
x_m, y_m = np.meshgrid(c_, r_, sparse=False, indexing='xy')
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# Get the boundingbox
x,y,w,h = cv2.boundingRect(c)
# calculate x,y coordinate of center
# Get the corresponding roi for calculation
weights = ori_img[y:y+h,x:x+w]
roi_grid_x = x_m[y:y+h,x:x+w]
roi_grid_y = y_m[y:y+h,x:x+w]
# get the weighted sum
weighted_x = weights * roi_grid_x
weighted_y = weights * roi_grid_y
cx = np.sum(weighted_x) / np.sum(weights)
cy = np.sum(weighted_y) / np.sum(weights)
推荐阅读
- python-3.x - PyTorch 1.9 命令等效于“zero_gradients”
- c# - How to Read with Message Body C# when Service Bus Explorer Adds junk http://schemas.microsoft.com/2003/10/Serialization when resubmitting messages -
- facebook - 线索广告的 Webhook 工作,但获取表单值的 api 调用不工作
- vue.js - Vuex - Unknown action type CreateProfile / ProfileList
- docusignapi - 实时 docusign 帐户上没有 Docusign 管理员
- java - Unable to get data from h2
- html - 有没有办法在播放后立即隐藏 HTML5 视频?
- android-studio - Webview:实施 shouldOverrideUrlLoading 后后退按钮不起作用
- angular - Transloco - 如何为翻译 API 添加范围?
- api - 您是否有关于事件数据响应的数据字典?