• 目标
  • 效果图
  • 操作说明
  • 代码

目标

探究肺癌患者的CT图像的图像特征并构建一个诊断模型

效果图


操作说明

代码中我以建立10张图为例,多少你自己定

准备工作:
1.准备肺癌或非肺癌每个各10张图,在本地创建一个名为“data”的文件夹,用于存放数据集。在“data”文件夹下创建两个子文件夹,分别命名为“cancer”和“non_cancer”,用于存放肺癌和非肺癌图像。将10张肺癌图像命名为“cancer_1.jpg”到“cancer_10.jpg”,并将它们放入“cancer”文件夹中。将10张非肺癌图像命名为“non_cancer_1.jpg”到“non_cancer_10.jpg”,并将它们放入“non_cancer”文件夹中。

  1. 在开始编写和执行代码之前,请确保已经安装完成以下库:

TensorFlow:用于构建和训练深度学习模型
Keras:用于快速构建和训练模型
scikit-learn:用于评估模型和数据预处理
numpy:用于数组和矩阵操作
OpenCV:用于处理和操作图像数据
matplotlib:用于可视化结果

安装命令

pip install tensorflow
pip install keras
pip install scikit-learn
pip install numpy
pip install opencv-python
pip install matplotlib

确保在本地创建了一个名为“data”的文件夹,并在其中创建了名为“cancer”和“non_cancer”的子文件夹。
将肺癌和非肺癌图像分别放入对应的子文件夹,并确保它们的命名正确

3.然后就可以复制上txt里面的代码进行执行了(记得改代码里面路径)

注意事情:
4. 图像大小:在load_images()函数中,已将图像调整为150x150大小。您可以根据实际情况更改此尺寸,但请注意,较大的图像可能会增加计算成本和训练时间。
例如,将图像大小调整为224x224:。

5.灰度图像:如果您的图像是灰度图像,可以将图像从单通道灰度转换为3通道灰度,以适应模型。在load_images()函数中添加如下代码

代码

import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from tensorflow.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical# 加载图像并调整大小
def load_images(data_dir, img_size): #从指定目录加载图像文件,并将它们转换成统一大小images = []labels = []for folder in os.listdir(data_dir): #遍历指定路径下的文件夹,其中 os.listdir(data_dir) 返回指定目录中所有文件和文件夹的名称列表for file in os.listdir(os.path.join(data_dir, folder)):img_path = os.path.join(data_dir, folder, file)img = cv2.imread(img_path)img = cv2.resize(img, img_size)images.append(img)labels.append(folder)return np.array(images), np.array(labels)# 构建模型
def create_model(input_shape, num_classes): #创建神经网络模型。函数接受输入数据的形状 input_shape 和分类数量 num_classes 作为参数model = Sequential() #将各个神经网络层按照顺序逐层叠加起来,构成一个“线性”模型model.add(Conv2D(32, (3, 3), activation='relu', input_shape=input_shape)) #添加了一个卷积层 Conv2D 到模型中 (3,3是滤波器大小)#接受输入张量(特征图),尺寸为 input_shape;#将每个滤波器应用于输入张量;#对每个输出结果应用 ReLU 非线性激活;#输出包括32张空间特征图通道model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(128, activation='relu'))model.add(Dropout(0.5))model.add(Dense(num_classes, activation='softmax'))model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])#optimizer=Adam() 指定使用 Adam 优化算法;#loss='categorical_crossentropy' 表示采用交叉熵作为损失函数,适合多分类问题;#metrics=['accuracy'] 说明度量模型性能时以准确率作为衡量标准return model# 主程序
def main():data_dir = r'F:\code_test\data'img_size = (150, 150)#这是图片的大小根据自己图片修改num_classes = 2batch_size = 4epochs = 50# 加载图像数据images, labels = load_images(data_dir, img_size)# 数据预处理images = images.astype('float32') / 255.0labels = (labels == 'cancer').astype(int)labels = to_categorical(labels, num_classes)# 划分训练集和测试集X_train, X_test, y_train, y_test = train_test_split(images, labels, test_size=0.2, random_state=42)# 数据增强datagen = ImageDataGenerator(horizontal_flip=True, vertical_flip=True)datagen.fit(X_train)# 创建模型model = create_model((img_size[0], img_size[1], 3), num_classes)# 训练模型history = model.fit(datagen.flow(X_train, y_train, batch_size=batch_size),validation_data=(X_test, y_test),steps_per_epoch=len(X_train) // batch_size,epochs=epochs)# 评估模型y_pred = model.predict(X_test)y_pred_classes = np.argmax(y_pred, axis=1)y_test_classes = np.argmax(y_test, axis=1)print("Classification Report:")print(classification_report(y_test_classes, y_pred_classes))print("Confusion Matrix:")print(confusion_matrix(y_test_classes, y_pred_classes))# 绘制训练过程的准确率和损失曲线def plot_training_history(history):plt.figure(figsize=(12, 4))plt.subplot(1, 2, 1)plt.plot(history.history['accuracy'], label='Training Accuracy')plt.plot(history.history['val_accuracy'], label='Validation Accuracy')plt.xlabel('Epoch')plt.ylabel('Accuracy')plt.legend()plt.subplot(1, 2, 2)plt.plot(history.history['loss'], label='Training Loss')plt.plot(history.history['val_loss'], label='Validation Loss')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()plt.show()plot_training_history(history)if __name__ == '__main__':main()

相关图片获取:
github链接
CSDN资源文件也有

探究肺癌患者的CT图像的图像特征并构建一个诊断模型相关推荐

  1. 【手把手教你】搭建神经网络(CT扫描3D图像的分类)

    大家好,我是羽峰,今天要和大家分享的是一个基于tensorflow的CT扫描3D图像的分类.文章会把整个代码进行分割讲解,完整看完,相信你一定会有所收获. 欢迎关注"羽峰码字" 目 ...

  2. [读论文]弱监督学习的精确 3D 人脸重建:从单个图像到图像集-Accurate 3D Face Reconstruction with Weakly-Supervised Learning:From

    论文地址:Accurate 3D Face Reconstruction with Weakly-Supervised Learning:From Single Image to Image Set ...

  3. 《OpenCV3编程入门》学习笔记5 Core组件进阶(二) ROI区域图像叠加图像混合

    第5章 Core组件进阶 5.2 ROI区域图像叠加&图像混合 5.2.1 感兴趣区域ROI(region of interest) 1.定义ROI区域两种方法: (1)定义矩形区域Rect: ...

  4. 使用Python,OpenCV制作图像Mask——截取ROIs及构建透明的叠加层

    使用Python,OpenCV制作图像Mask--截取ROIs及构建透明的叠加层 1. 效果图 2. 源码 参考 这篇博客将介绍如何使用OpenCV制作Mask图像掩码.使用位运算和图像掩码允许我们只 ...

  5. Python计算机视觉——图像到图像的映射

    Python计算机视觉--图像到图像的映射 文章目录 Python计算机视觉--图像到图像的映射 写在前面 1 单应性变换 1.1 直接线性变换算法 1.2 仿射变换 2 图像扭曲 2.1 图像中的图 ...

  6. 让机器“看见”:图像数据的特征提取方法

    ↑↑↑关注后"星标"Datawhale 每日干货 & 每月组队学习,不错过 Datawhale干货 作者:谢雨飞,趣头条算法工程师 图像特征主要有图像的颜色特征.纹理特征. ...

  7. 只用一张训练图像进行图像的恢复

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 作者:George Seif 编译:ronghuaiyang 导读 ...

  8. Seaborn可视化图像调整图像大小(figure size)方法实战(Adjust the Figure Size)

    Seaborn可视化图像调整图像大小(figure size)方法实战(Adjust the Figure Size) 目录 Seaborn可视化图像调整图像大小(figure size)方法实战(A ...

  9. 真·无监督!延世大学提出图像到图像无监督模型,实验结果超SOTA

    图像翻译目的是用模型将源域图像转换到目标域图像,通常涉及标签图到场景图的转换.图像风格.人脸的属性变换.标签图到场景图的转换. 图像翻译任务自生成对抗网络提出就得到了快速发展,例如经典的pix2pix ...

最新文章

  1. 如何将自己写的verilog模块封装成IP核(二)
  2. python日历提醒_Python之时间:calender模块(日历)
  3. 王道计算机考研 计算机组成原理 第二章、数据的表示和运算
  4. mega5安装包_[MEGA DEAL] 2017年完全Java捆绑包(95%折扣)
  5. 我的世界linux开服权限不足,我的世界路由器开服怎么获得超级管理员权限
  6. 抓取Web网页数据分析
  7. 让刺猬和狐狸结婚:资本巨鳄BlackRock的金融科技野心
  8. 网络编程day1-本地信息的获取
  9. 云南农职《JavaScript交互式网页设计》 综合机试试卷⑥——简易旅游网
  10. 南开大学2019年高等代数考研试题讲解
  11. Qt编写的开源帖子集合(懒人专用)
  12. Centos7登陆颜色修改#PS1
  13. PC - 电脑应该多久清洁一次?
  14. 如何动态使用烘焙出来的ReflectionProbe-0.exr信息
  15. 淘宝商城首页鼠标经过整个区域图片变暗变亮的JS特效代码
  16. python django 动态网页_Django创建动态网页的基础知识
  17. 3D游戏建模师的工资和发展前景到底怎么样?
  18. C语言农历天干地支,农历一百年算法(1921~2021)【C语言代码】
  19. RAID 5数据恢复图解
  20. 2019—猪年的愚人节

热门文章

  1. 牛客网 http://www.nowcoder.com/test/question/done?tid=2198842qid=14753#summary
  2. 「SequoiaDB巨杉数据库」getSlave()
  3. 在 Apache Tomcat 服务器上启用 HTTPS 或 SSL 正确方式的分步指南 – 端口 8443
  4. c++标准库sstream的用法
  5. Kubernetes学习-K8S安装篇-集群安装网段划分
  6. C语言execlp函数
  7. canvas将上传的图片文件绘制一个空心圆并往里加个图片,解决canvas绘制jpeg,jpg图片背景变黑为题
  8. 使用px2rem不生效
  9. 前端每周清单第 43 期:2017 JavaScript 回顾、Rust 与 WebAssembly 开发游戏
  10. java 中文替换,Java字符串的替换