如何一次性将多张图像转换为Tensor?
批量转换图像为形状(10,54,54,3)的Tensor
方法1:手动批量处理后转换
先遍历所有图像路径,完成读取、尺寸调整后存入列表,最后一次性转换为Tensor:
import cv2, glob import tensorflow as tf # 获取所有目标图像路径 img_paths = glob.glob("images/*jpg") # 定义统一目标尺寸 target_size = (54, 54) processed_imgs = [] for path in img_paths: # 读取图像 img = cv2.imread(path) # 跳过读取失败的图像(避免报错) if img is None: continue # 调整尺寸(cv2.resize参数为(width, height),对应目标尺寸的(w,h)) resized_img = cv2.resize(img, target_size) processed_imgs.append(resized_img) # 转换为Tensor,自动生成为(N,54,54,3)形状(N为有效图像数量) batch_tensor = tf.convert_to_tensor(processed_imgs, dtype=tf.int64) print(batch_tensor.shape) # 输出 (10, 54, 54, 3)(假设10张都读取成功)
方法2:用TensorFlow原生API批量处理
如果不想依赖OpenCV,可直接用TF的图像读取接口完成批量操作,代码更简洁:
import tensorflow as tf import glob img_paths = glob.glob("images/*jpg") target_size = (54, 54) def load_and_preprocess(img_path): # 读取图像文件 img_raw = tf.io.read_file(img_path) # 解码为RGB格式图像(和OpenCV的BGR通道顺序不同,按需调整) img = tf.image.decode_jpeg(img_raw, channels=3) # 调整尺寸 img_resized = tf.image.resize(img, target_size) # 转换为和单张处理一致的int64类型 return tf.cast(img_resized, tf.int64) # 批量处理所有路径并转换为Tensor batch_tensor = tf.convert_to_tensor([load_and_preprocess(path) for path in img_paths]) print(batch_tensor.shape) # 输出 (10, 54, 54, 3)
关键注意点
- OpenCV默认读取图像为BGR通道顺序,若后续需和TensorFlow模型配合,建议添加通道转换:
resized_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB) - 务必处理读取失败的图像(比如损坏文件),避免
None值导致转换Tensor时报错
内容的提问来源于stack exchange,提问作者Sourav
相关产品推荐
相关产品推荐

