遇到TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
frame=cv2.resize(frame,(1020,500)) results=model.predict(frame) # print(results) # a=results[0].boxes.boxes a=results[0].boxes.data print('type(a):',type(a)) # <class 'torch.Tensor'> a=a.cpu() #如果没有这一行语句,会持续报错! print('a.cpu()成功') print('type(a):', type(a)) # <class 'torch.Tensor'>,类型不变,只是从gpu上面赚到了cpu上面 px=pd.DataFrame(a).astype("float")
代码段中的变量a是模型的检测输出结果,类型是<class 'torch.Tensor'>,但是在使用px=pd.DataFrame(a).astype("float")将其转换为Pandas DataFrame数据结构,并同时将其转换为浮点数数据类型。
但是这个pd.DataFrame(a)方法,只能处理cpu上面的数据(即内存里面的数据)。但是此时的变量a是模型的检测结果,还在GPU上面(即显存里面的数据)。故而报错。
添加语句:a=a.cpu()将变量a从GPU移动到CPU上进行处理。成功解决报错。