我有多个圆圈的图像,圆圈内有热点区域,强度高(高像素值),而区域有冷点(低像素值)。我想用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 /灰度图像(考虑像素强度)而不是二进制图像的加权质心。我怎样才能做到这一点?
谢谢!
答案 0 :(得分:0)
这是您问题的一种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)
答案 1 :(得分:0)
对@ 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(r_, c_, 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
cy = np.sum(weighted_x) / np.sum(weights)
cx = np.sum(weighted_y) / np.sum(weights)