【问题标题】:calculate a centroid with opencv用opencv计算质心
【发布时间】:2019-05-12 04:11:47
【问题描述】:

我有多个圆圈的图像,圆圈内有热点区域,高强度(高像素值)和冷点区域(低像素值)。我想用 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/灰度图像(考虑像素强度)的加权质心,而不是二值图像。我怎样才能做到这一点?

谢谢!

【问题讨论】:

  • 我认为OpenCV可以取图像的强度值。因此,您需要创建具有所需强度的轮廓点的图像。我还没有尝试过,但它可能很容易测试......如果它是RGB,那么你可以尝试先将其转换为灰度以获得强度,或使用其他类型的权重,如饱和度或亮度

标签: python opencv centroid


【解决方案1】:

这是您问题的一种 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)  

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2015-12-27
      • 2015-06-04
      • 1970-01-01
      • 2012-04-06
      • 2022-11-21
      • 2018-03-02
      • 2021-06-13
      • 2012-02-22
      相关资源
      最近更新 更多