首页 > 解决方案 > 用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/灰度图像(考虑像素强度)的加权质心,而不是二值图像。我怎样才能做到这一点?

谢谢!

标签: pythonopencvcentroid

解决方案


对@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)  

推荐阅读