Tensorflow学习笔记-tf.image.resize_images() 调整图片大小

本文介绍了一种使用TensorFlow进行图片预处理的方法,重点在于如何调整图片尺寸以适应卷积神经网络(CNN)等深度学习模型的输入要求。通过实际代码演示了从读取原始图片到调整至特定尺寸的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用自己的图片做数据集时需要做相应的处理(缩/放)

因此在使用CNN等模型之前,可以使用该方法获得你想要的大小的图片数据

import matplotlib.pyplot as plt  
import tensorflow as tf  
import numpy as np  
  
image_raw_data = tf.gfile.GFile('C:/Users/DELL/Desktop/CWTPic/train1.jpg','r').read()   #加载原始图像  
  
with tf.Session() as sess:  
    img_data = tf.image.decode_jpeg(image_raw_data)   #解码
    plt.imshow(img_data.eval())  
    plt.show()
    resized = tf.image.resize_images(img_data, [64,64],method=0)  #第一个参数为原始图像,第二个参数为图像大小,第三个参数给出了指定的算法  
    resized = np.asarray(resized.eval(),dtype='uint8')  #变为uint8才能显示
    plt.imshow(resized)   
    plt.show()


### 使用 Docker 实现图像识别项目 #### 准备工作 为了在 Docker 中实现图像识别项目,首先需要准备必要的资源和工具。这包括安装 Docker 和配置开发环境。 确保已经安装了最新版本的 Docker[^1]。对于基于 Python 的机器学习框架,如 TensorFlow 或 PyTorch,推荐使用带有预装 Anaconda 发行版的 GPU 支持 Docker 镜像来加速模型训练过程[^3]。 #### 创建自定义 Dockerfile 创建一个新的文件夹用于存储所有的项目文件,在该目录下新建名为 `Dockerfile` 的文本文件: ```dockerfile FROM nvidia/cuda:10.1-cudnn7-devel-ubuntu18.04 # 安装基本依赖项 RUN apt-get update && \ apt-get install -y python3-pip git wget bzip2 ca-certificates libglib2.0-0 libsm6 libxext6 libxrender-dev # 设置工作目录 WORKDIR /workspace # 复制当前文件夹的内容至容器内的工作空间 COPY . . # 下载并设置 Miniconda 环境 RUN wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh && \ bash ~/miniconda.sh -b -p /opt/conda && \ rm ~/miniconda.sh && \ echo "export PATH=/opt/conda/bin:$PATH" >> ~/.bashrc && \ source ~/.bashrc ENV PATH="/opt/conda/bin:${PATH}" # 创建 conda 虚拟环境 RUN conda create -n tf_env tensorflow-gpu=2.3 opencv-python matplotlib jupyter notebook scikit-image pandas numpy scipy seaborn requests pillow h5py keras-preprocessing imgaug albumentations pyyaml cython opt-einsum gast wrapt grpcio absl-py termcolor protobuf astor six mock wheel setuptools typing_extensions contextlib2 futures portpicker markdown google-pasta tensorboard tb-nightly werkzeug gin-config kaggle gdown --yes && \ conda activate tf_env # 激活虚拟环境中启动 Jupyter Notebook 服务器命令 CMD ["jupyter", "notebook", "--port=8888", "--no-browser", "--ip=0.0.0.0", "--allow-root"] ``` 此脚本会拉取 NVIDIA CUDA 开发者镜像作为基础,并在其上安装所需的软件包以及建立适合运行 TensorFlow 的 Conda 环境。 #### 编写 Python 代码进行图像分类 接下来编写一段简单的 Python 代码来进行图像分类任务。假设有一个预先训练好的卷积神经网络 (CNN),可以从本地磁盘读取图片完成预测操作。 ```python import os from PIL import Image import numpy as np import tensorflow as tf from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions def load_image(img_path): """加载单张图片""" img = Image.open(img_path).resize((224, 224)) x = np.array(img) X = np.expand_dims(x, axis=0) return preprocess_input(X) if __name__ == '__main__': model = ResNet50(weights='imagenet') test_dir = './test_images' files = [os.path.join(test_dir, f) for f in os.listdir(test_dir)] for file_name in files: processed_img = load_image(file_name) preds = model.predict(processed_img) print(f'Predicting {file_name}: ') decoded_preds = decode_predictions(preds, top=3)[0] for (_, label, prob) in decoded_preds: print(f'- Label={label}, Probability={prob:.2f}') ``` 这段程序利用 Keras 提供的应用接口快速实例化了一个 ResNet50 模型,并对其进行了初始化权重加载。之后遍历指定路径下的所有测试集图片,逐一对它们执行推理运算得到最终的结果输出[^4]。 #### 运行容器和服务 构建上述描述的 Docker 映像并将源码复制进去后,可以通过如下指令启动交互式的笔记本界面: ```shell $ docker build -t my-tensorflow-app . $ docker run -it --rm --gpus all -v $(pwd):/workspace -p 8888:8888 my-tensorflow-app ``` 此时应该可以在浏览器地址栏访问 http://localhost:8888 查看正在运行的服务页面。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值