• tensorflow的unet模型


    1. import tensorflow as tf
    2. from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Dropout, UpSampling2D, concatenate
    3. # 定义 U-Net 模型
    4. def unet(input_size=(256, 256, 3)):
    5. inputs = Input(input_size)
    6. # 编码器部分
    7. conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(inputs)
    8. conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv1)
    9. pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
    10. conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool1)
    11. conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv2)
    12. pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
    13. conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool2)
    14. conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv3)
    15. pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
    16. conv4 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool3)
    17. conv4 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv4)
    18. drop4 = Dropout(0.5)(conv4)
    19. pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)
    20. # 中间层
    21. conv5 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool4)
    22. conv5 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv5)
    23. drop5 = Dropout(0.5)(conv5)
    24. # 解码器部分
    25. up6 = Conv2D(512, 2, activation='relu', padding='same', kernel_initializer='he_normal')(UpSampling2D(size=(2, 2))(drop5))
    26. merge6 = concatenate([drop4, up6], axis=3)
    27. conv6 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge6)
    28. conv6 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv6)
    29. up7 = Conv2D(256, 2, activation='relu', padding='same', kernel_initializer='he_normal')(UpSampling2D(size=(2, 2))(conv6))
    30. merge7 = concatenate([conv3, up7], axis=3)
    31. conv7 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge7)
    32. conv7 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv7)
    33. up8 = Conv2D(128, 2, activation='relu', padding='same', kernel_initializer='he_normal')(UpSampling2D(size=(2, 2))(conv7))
    34. merge8 = concatenate([conv2, up8], axis=3)
    35. conv8 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge8)
    36. conv8 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv8)
    37. up9 = Conv2D(64, 2, activation='relu', padding='same', kernel_initializer='he_normal')(UpSampling2D(size=(2, 2))(conv8))
    38. merge9 = concatenate([conv1, up9], axis=3)
    39. conv9 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge9)
    40. conv9 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv9)
    41. outputs = Conv2D(1, 1, activation='sigmoid')(conv9)
    42. model = tf.keras.Model(inputs=inputs, outputs=outputs)
    43. return model
    44. # 创建 U-Net 模型
    45. model = unet()
    46. model.summary()

    一个简单的 U-Net 模型的 TensorFlow 2.x 代码示例。U-Net 模型通常用于图像分割任务。

    需要提前准备好train_imagestrain_masks变量,它们分别包含训练图像和对应的分割掩膜。

    1. import tensorflow as tf
    2. import numpy as np
    3. from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Dropout, UpSampling2D, concatenate
    4. from tensorflow.keras.models import Model
    5. from tensorflow.keras.optimizers import Adam
    6. from sklearn.model_selection import train_test_split
    7. # 定义 U-Net 模型
    8. def unet(input_size=(256, 256, 3)):
    9. inputs = Input(input_size)
    10. # 编码器部分
    11. conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(inputs)
    12. conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv1)
    13. pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
    14. conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool1)
    15. conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv2)
    16. pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
    17. # ...(更多的编码器层)
    18. # 底层
    19. conv5 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool4)
    20. conv5 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv5)
    21. drop5 = Dropout(0.5)(conv5)
    22. # 解码器部分
    23. up6 = UpSampling2D(size=(2, 2))(drop5)
    24. up6 = Conv2D(512, 2, activation='relu', padding='same', kernel_initializer='he_normal')(up6)
    25. merge6 = concatenate([drop4, up6], axis=3)
    26. conv6 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge6)
    27. conv6 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv6)
    28. # ...(更多的解码器层)
    29. # 输出层
    30. conv10 = Conv2D(1, 1, activation='sigmoid')(conv9)
    31. model = Model(inputs=inputs, outputs=conv10)
    32. return model
    33. # 准备训练数据和标签
    34. # 这里假设你已经有了医学图像数据集,以及相应的分割标签
    35. # 请根据你的数据集的格式来加载和预处理数据
    36. # 假设训练数据和标签分别存储在 train_images 和 train_masks 中
    37. # 划分训练集和验证集
    38. X_train, X_val, y_train, y_val = train_test_split(train_images, train_masks, test_size=0.2, random_state=42)
    39. # 创建 U-Net 模型
    40. model = unet(input_size=(256, 256, 1)) # 修改为你的输入图像尺寸
    41. # 编译模型
    42. model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])
    43. # 训练模型
    44. model.fit(X_train, y_train, batch_size=4, epochs=10, validation_data=(X_val, y_val))
    45. # 保存模型
    46. model.save("unet_medical_segmentation.h5")

    上代码中省略了一些编码器和解码器层的详细实现,这些层应该是对称的,并且解码器部分的每一层都应该与编码器部分的相应层进行连接(跳跃连接)。

    你需要根据你的具体需求添加更多的编码器和解码器层。

    此外,训练数据和标签的加载和预处理步骤需要根据你的数据集格式进行相应的调整。如果你的标签是多分类的,你可能需要将最后一层的激活函数从sigmoid改为softmax,并且调整损失函数为categorical_crossentropy。如果你的图像是单通道的(例如灰度图),则需要确保输入大小的通道数为1。

     

    在加载和预处理医学图像数据时,可以使用 Python 中的图像处理库如 OpenCV 或 Pillow。调整大小和预处理医学图像的示例代码

    1. import cv2
    2. import numpy as np
    3. def load_and_preprocess_image(image_path, target_size=(256, 256)):
    4. # 读取图像
    5. image = cv2.imread(image_path)
    6. # 如果需要,调整图像大小
    7. if target_size is not None:
    8. image = cv2.resize(image, target_size)
    9. # 预处理图像(根据你的需求进行进一步的预处理,如归一化)
    10. image = image / 255.0 # 归一化到 [0, 1] 范围
    11. return image
    12. # 示例用法:
    13. image_path = "your_image.jpg" # 替换成你的图像文件路径
    14. target_size = (256, 256) # 替换成你想要的目标大小
    15. # 加载和预处理图像
    16. preprocessed_image = load_and_preprocess_image(image_path, target_size)
    17. # 打印图像的形状(用于验证)
    18. print("Image shape:", preprocessed_image.shape)

    它遍历目录中的图像文件,加载并预处理这些图像,然后将它们转换为 TensorFlow 张量

    1. import tensorflow as tf
    2. import os
    3. import cv2
    4. import numpy as np
    5. def load_and_preprocess_image(image_path, target_size=(256, 256)):
    6. # 读取图像
    7. image = cv2.imread(image_path)
    8. # 如果需要,调整图像大小
    9. if target_size is not None:
    10. image = cv2.resize(image, target_size)
    11. # 预处理图像(根据你的需求进行进一步的预处理,如归一化)
    12. image = image / 255.0 # 归一化到 [0, 1] 范围
    13. return image
    14. def load_and_preprocess_images_in_directory(directory, target_size=(256, 256)):
    15. images = []
    16. # 遍历目录中的图像文件
    17. for filename in os.listdir(directory):
    18. if filename.endswith(".jpg") or filename.endswith(".png"):
    19. image_path = os.path.join(directory, filename)
    20. preprocessed_image = load_and_preprocess_image(image_path, target_size)
    21. images.append(preprocessed_image)
    22. # 将图像列表转换为 TensorFlow 张量
    23. images = np.array(images)
    24. images = tf.convert_to_tensor(images, dtype=tf.float32)
    25. return images
    26. # 示例用法:
    27. image_directory = "your_image_directory" # 替换成包含图像的目录路径
    28. target_size = (256, 256) # 替换成你想要的目标大小
    29. # 加载和预处理图像
    30. image_tensor = load_and_preprocess_images_in_directory(image_directory, target_size)
    31. # 打印图像张量的形状(用于验证)
    32. print("Image tensor shape:", image_tensor.shape)

     

     

  • 相关阅读:
    什么是好代码/坏代码?给普通人的图解示例
    网络基本概念
    《安富莱嵌入式周报》第291期:分分钟设计数字芯片,单片机版JS,神经网络DSP,microPLC,FatFS升级至V0.15,微软Arm64 VS正式版发布
    STC51单片机34——五线四相步进电机驱动(1个步进电机)
    工业设计:产品配色与产品形态的关系
    [附源码]Python计算机毕业设计超市团购平台
    第十一章、python的异常处理------raise异常处理、assert异常处理、异常类BaseException、关键字as的用法
    Scala语言基础
    一站式低代码开发平台iVX初探
    Python编程规范+最佳实践
  • 原文地址:https://blog.csdn.net/qq_35827483/article/details/132914200