社交距离检测移质心连线到足部出现TypeError: iteration over a 0-d tensor如何解决
问题原因
- 语法错误导致Tensor报错:你调用
max函数时括号位置写错,int(max(i[3]), (i[1]))的写法相当于给max只传入了i[3]一个参数,返回0维张量后,int()函数把第二个参数i[1]识别为进制参数,触发类型错误。 - 连线端点未同步修改:
distancing函数中计算连线端点cntr1、cntr2时,仍然使用人体框垂直中心的y坐标,没有和你修改后的足部质心逻辑对齐,所以连线位置和质心不匹配。
修复方案
1. 修正max函数语法
将所有max(i[3]), (i[1])的写法修改为max(i[3], i[1]),如果people_coords中的元素是PyTorch张量,需要额外调用.item()方法转成普通数值,避免后续计算报错。
2. 同步修改连线端点的计算逻辑
将distancing函数中cntr1、cntr2的y坐标计算规则,和plot_dots_on_people中的质心计算规则保持一致。
优化建议
可以把足部坐标提取逻辑封装为独立工具函数,避免两处重复写相同逻辑,降低后续修改成本。
修改后代码示例
公共工具函数(可选,用于简化代码)
def get_foot_center(xyxy): # 统一处理张量/普通数值输入,返回人体足部中心点坐标 x1 = int(xyxy[0].item() if hasattr(xyxy[0], 'item') else xyxy[0]) x2 = int(xyxy[2].item() if hasattr(xyxy[2], 'item') else xyxy[2]) y1 = int(xyxy[1].item() if hasattr(xyxy[1], 'item') else xyxy[1]) y2 = int(xyxy[3].item() if hasattr(xyxy[3], 'item') else xyxy[3]) return ((x1 + x2) // 2, max(y2, y1))
修正后的distancing函数
import itertools import cv2 def distancing(people_coords, img, dist_thres_lim=(200,250)): # Plot lines connecting people already_red = dict() # dictionary to store if a plotted rectangle has already been labelled as high risk centers = [] for i in people_coords: centers.append(get_foot_center(i)) for j in centers: already_red[j] = 0 x_combs = list(itertools.combinations(people_coords,2)) radius = 10 thickness = 5 for x in x_combs: xyxy1, xyxy2 = x[0],x[1] # 直接调用封装好的方法获取足部坐标,保证和质心位置完全对齐 cntr1 = get_foot_center(xyxy1) cntr2 = get_foot_center(xyxy2) dist = ((cntr2[0]-cntr1[0])**2 + (cntr2[1]-cntr1[1])**2)**0.5
修正后的plot_dots_on_people函数
def plot_dots_on_people(x, img): # Plotting centers of people with green dot. thickness = -1 color = [0, 255, 0] # green center = get_foot_center(x) radius = 10 cv2.circle(img, center, radius, color, thickness)
内容的提问来源于stack exchange,提问作者Hesti Media Tama
相关产品推荐
相关产品推荐

