TensorFlow将128×128 MRI图像转为224×224的实现方法问询
关于TensorFlow图像尺寸转换与像素拆分的问题
我在CNN项目中使用Kaggle的MRI预处理数据集,该数据集包含128×128像素的.jpg图像。参考资料里会把数据集设置为224×224像素的image_size来使用,我用了以下代码,修改img_height和img_width在128×128和224×224之间切换时,程序能正常运行且有明显变化,推测尺寸转换是在这段代码中完成的:
batch_size = 32 img_height = 224 img_width = 224 from tensorflow.keras.utils import image_dataset_from_directory train_data = image_dataset_from_directory( data_dir, validation_split=0.2, subset="training", seed=123, image_size=(img_height, img_width), batch_size=batch_size) val_data = image_dataset_from_directory(data_dir, validation_split=0.2, subset="validation", seed=123, image_size=(img_height,img_width), batch_size=batch_size)
我的疑问:
- TensorFlow实现这种尺寸转换的具体方法是什么?
- TensorFlow能否识别特定像素的颜色并将其独立拆分为多个像素?
一、尺寸转换的具体实现
你的推测完全正确,图像尺寸转换就是通过image_dataset_from_directory的image_size参数自动完成的,底层逻辑是:
- 加载图像时,TensorFlow会调用
tf.image.resize函数对原图像进行缩放 - 默认采用双线性插值算法,它会基于原图像相邻像素的数值,计算出目标尺寸下每个新像素的取值,能保证缩放后的图像过渡平滑,很适合MRI这类医疗图像的尺寸调整
- 整个过程嵌入在数据加载流水线中,不需要你手动写额外的缩放代码,只要设置好目标尺寸
(img_height, img_width)即可
二、特定颜色像素的拆分处理
TensorFlow可以实现识别特定颜色像素并拆分的需求,但不能通过image_dataset_from_directory直接完成,需要添加自定义的处理步骤:
- 识别特定颜色:通过像素值匹配实现,比如定义目标颜色的阈值范围,用
tf.where筛选出符合条件的像素位置 - 拆分或扩展像素:
- 如果是要把特定颜色的像素单独提取为新的图像/通道:可以先生成布尔掩码标记目标像素,再将掩码转为可视化的图像
- 如果是要把单个特定像素拆分为多个像素:可以用
tf.tile复制像素,或者通过插值方式扩展像素区域 - 把处理逻辑集成到数据流水线:在
image_dataset_from_directory之后用map函数添加自定义处理,示例代码如下:def process_image(image, label): # 识别接近黑色的像素(RGB值均小于50) mask = tf.reduce_all(image < 50, axis=-1) # 将掩码转为3通道图像,作为拆分后的结果 split_image = tf.cast(mask, tf.float32)[..., tf.newaxis] * 255 # 若要把单个目标像素扩展为3x3区块,可使用tf.tile # target_pixels = image[mask] # expanded_pixels = tf.tile(tf.expand_dims(tf.expand_dims(target_pixels, 0), 0), [3, 3, 1]) return image, split_image, label # 将处理逻辑应用到训练数据集 train_data = train_data.map(process_image)
内容的提问来源于stack exchange,提问作者Rafi Zaidan
相关产品推荐
相关产品推荐

