如何将图像数据类型从uint8转为torch.float?遍历图像循环遇异常
问题修复方案
先明确你代码里的几个核心错误:
cv2.imread的路径缺少.png后缀,大概率读不到后续的图像文件- 搞反了numpy数组与PyTorch Tensor的转换逻辑:
torch.to_numpy()是Tensor转numpy数组的方法,而你需要把cv2读取的numpy数组转成Tensor,应该用torch.from_numpy() - 错误使用
image[i]:这是在取单张图像的第i行像素,而非处理第i张图像 to(dtype = torch)写法错误,必须指定具体数据类型,比如torch.uint8或torch.float32
修正后的代码示例(按序号遍历图像)
import cv2 import torch # 替换为你的实际图像数量 IMAGE_COUNT = 10 # 替换为你的目标文件夹路径 FOLDER_PATH = "DIR/FOLDER" for i in range(IMAGE_COUNT): # 加上.png后缀,确保读取正确的文件 image = cv2.imread(f"{FOLDER_PATH}/{i}.png") # 校验图像是否成功读取 if image is None: print(f"警告:未找到或无法读取图像 {i}.png") continue # 将numpy数组转为PyTorch Tensor tensor_image = torch.from_numpy(image) # 按需转换数据类型(保留uint8则可跳过此行) tensor_image = tensor_image.to(dtype=torch.float32) # 此处添加你的后续处理逻辑 print(f"处理第{i}张图像,Tensor形状:{tensor_image.shape}")
更稳妥的遍历方式(按文件列表遍历)
如果你的图像文件名不是连续数字序号,建议直接遍历文件夹内的所有PNG文件:
import os import cv2 import torch FOLDER_PATH = "DIR/FOLDER" # 遍历文件夹下所有PNG文件 for filename in os.listdir(FOLDER_PATH): if filename.endswith(".png"): image_path = os.path.join(FOLDER_PATH, filename) image = cv2.imread(image_path) if image is None: print(f"警告:无法读取图像 {filename}") continue tensor_image = torch.from_numpy(image).to(dtype=torch.float32) print(f"处理图像 {filename},Tensor形状:{tensor_image.shape}")
内容的提问来源于stack exchange,提问作者Pratham Grover
相关产品推荐
相关产品推荐

