Jetson人流分析项目Python类型错误求助:数组转标量失败
错误修复指导:TypeError: only size-1 arrays can be converted to Python scalars
错误原因分析
报错出现在这行代码:
self.__img = self.draw_grid_in_cam(int(self.__img), int(self.__conf_px_per_ft))
两个核心问题:
self.__img是代表图像的多维numpy数组(比如形状为(高度, 宽度, 3)的像素矩阵),int()函数无法将整个图像数组转换为整数,这完全是多余且错误的操作。self.__conf_px_per_ft如果是numpy数组(哪怕是单元素数组,比如array([15])),直接用int()转换也会触发错误——int()仅支持单个数值或size为1的数组且需以标量形式传入,而numpy数组需要先提取内部的标量值。
修复代码
直接修改出错的代码块:
if self.__calibrated_flag: # 处理conf_px_per_ft:从numpy数组提取标量再转int(如果是numpy类型的话) conf_px_value = self.__conf_px_per_ft.item() if hasattr(self.__conf_px_per_ft, 'item') else self.__conf_px_per_ft conf_px_int = int(conf_px_value) # 去掉self.__img的int转换,直接传入图像数组 self.__img = self.draw_grid_in_cam(self.__img, conf_px_int)
关键说明
- 图像参数
self.__img不需要任何转换,draw_grid_in_cam方法本身就是用来处理图像数组的,直接传入即可。 - 对
self.__conf_px_per_ft,用.item()可以从单元素numpy数组中提取Python原生数值(比如从array([10])拿到10),之后再转int就不会触发类型错误。如果它本身已经是Python原生数值(比如int或float),hasattr判断会跳过.item()调用,直接转int即可。
内容的提问来源于stack exchange,提问作者delphine
相关产品推荐
相关产品推荐

