使用opencv计算质心

fv2wmkja  于 2022-11-15  发布在  其他
关注(0)|答案(2)|浏览(258)

我有一个多个圆的图像,在圆内有热点区域,具有高强度(高像素值)和冷点区域(低像素值)。我想用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/灰度图像的加权质心(考虑了像素强度),而不是二进制图像。我怎么做呢?
谢谢你,谢谢你

yvt65v4c

yvt65v4c1#

这里是一种python伪代码解决你的问题。代码是设计来计算质心的加权中心。图像的强度级别在计算中被用作权重。因此,强度越高,权重越高。
为了简化计算过程,我们需要有原始图像大小的x坐标和y坐标网格,x和y坐标的加权平均值将为您提供加权质心

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='ij')

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(roi_grid_y) / np.sum(weights)
5lhxktic

5lhxktic2#

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

相关问题