Advertisement

使用OpenCV进行肺炎诊断检测

阅读量:

该文本介绍了一种使用OpenCV和深度学习(如VGG16卷积神经网络)来检测胸部X光片中肺炎的系统。首先,文中详细说明了如何通过Python代码安装OpenCV,并展示了如何从Kaggle下载并准备用于训练的胸部X光图像数据集。数据增强技术被用于生成更多训练样本,以提高模型性能。接着,文中描述了如何利用ImageDataGenerator加载和预处理训练数据,并使用Keras的模型构建工具训练一个二分类模型,以区分肺炎和正常图像。训练过程中,模型通过Adam优化器和二元交叉熵损失函数进行,训练了10个时期。最后,模型在测试集上进行了评估,并展示了部分正确和错误分类的实例。整个过程展示了如何利用计算机视觉和深度学习技术来辅助医疗诊断,提高诊断效率和准确性。

6bc47da719cf73081a69bd8c490335dd.jpeg

肺炎是一种因感染而引起的致命的呼吸道疾病,尤其在高危人群群体中,可能会导致致命的并发症。为了最大限度地提高患者的康复率,必须尽快进行诊断和治疗。

诊断过程具有一定的难度,这需要配备必要的医学实验室设备和高超的医疗技术。然而,我们可以通过借助深度学习以及计算机视觉技术,开发出一个高效且操作简便的检测工具,从而帮助医生快速准确地识别肺炎。

我们采用OpenCV(https://opencv.org/)这一开源计算机视觉和机器学习软件库,以创建适用于图像和视频分析的应用程序,例如X射线成像系统。该库专为执行计算机视觉、机器学习和图像处理任务而设计,提供丰富的功能和工具。

在本课中,我们将了解如何使用 OpenCV 识别胸部 X 光图像中的肺炎。

安装 OpenCV

安装OpenCV被视为项目启动的第一步。不同操作系统提供了多种安装OpenCV的途径,以下是一些广为采用的方案:

Windows品牌用户可访问OpenCV (https://opencv.org/releases/) 官方网站,获取经过优化的二进制文件资源。

在 Linux 发行版中,可以通过其内置的包管理器安装 OpenCV 程序。为了在终端中执行安装指令,例如在 Ubuntu 系统上。

复制代码
    Install libopencv-dev with sudo apt-get

Mac OS:可以使用 Homebrew 设置 OpenCV,应在终端中输入以下代码。

复制代码
    Brew install opencv

加载 OpenCV 后,你可以使用以下 Python 代码检查它是否正常工作。

复制代码
 import cv2

    
 print(cv2.__version__)

如果正确安装了 OpenCV,你应该会在终端中看到版本号。

下载数据集

现在可以获取用于训练肺炎检测模型的数据集。在本次练习中,我们将使用取自 Kaggle 的胸部 X-ray影像(肺部感染病例)数据集。

数据集:https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia

数据集中共有 5,856 张胸部 X 光图像,分为肺炎和正常两类。

为了获取该数据集,您需要先注册 Kaggle 账户并同意其使用条款。完成后,请在终端中输入以下命令以获取数据集:

复制代码
    kaggle datasets download -d paultimothymooney/chest-xray-pneumonia

首先在本地计算机上创建一个子文件夹然后从该子文件夹中提取ZIP文件。

准备数据

然后,我们需要为肺炎识别模型的训练任务准备数据。为了生成额外的训练样本,我们将采用数据增强技术。

该操作旨在优化模型性能并加速模型构建过程。数据增强通过实施随机变换对图像进行处理,如旋转、缩放和翻转,从而生成不同版本。

我们将搭建两个目录,用于数据准备工作。其中一部分专门用于训练图片,另一部分则用于验证图像。其中80%的图片将分配给训练数据集,剩下的20%则用于验证。

这是准备信息的代码:

复制代码
 import os

    
 import shutil
    
 import random
    
  
    
 # Define the paths
    
 input_dir = 'path/to/input/dir'
    
 train_dir = 'path/to/train/dir'
    
 val_dir = 'path/to/val/dir'
    
  
    
 # Create the directories
    
 os.makedirs(train_dir, exist_ok=True)
    
 os.makedirs(val_dir, exist_ok=True)
    
  
    
 # Get the list of images
    
 image_paths = []
    
 for root, dirs, files in os.walk(input_dir):
    
     for file in files:
    
         if file.endswith('.jpeg'):
    
             image_paths.append(os.path.join(root, file))
    
  
    
 # Shuffle the images
    
 random.shuffle(image_paths)
    
  
    
 # Split
    
  
    
 split_idx = int(0.8 * len(image_paths))
    
 train_image_paths = image_paths[:split_idx]
    
 val_image_paths = image_paths[split_idx:]

请将图像复制到目标目录中。请将“path/to/input/dir”设置为你在此代码中提取信息的目录路径。为了分别保存训练和验证图像的目录路径,请将它们替换为“path/to/train/dir”和“path/to/val/dir”。

精准跟踪和记录复杂的实验参数对于确保模型训练的可追溯性至关重要。 Comet 工具箱中的一个工具,它帮助简化模型管理。 通过探索 PetCam 场景,深入了解如何利用 Comet 的功能来优化模型开发。

训练模型

基于我们上一阶段构建的训练图像集合,当前任务要求我们专注于训练一种肺炎检测模型。其中,模型的核心组件将采用VGG16这一预训练的卷积神经网络架构,这一选择基于其在图像识别任务中的有效性。

广泛应用于图像识别任务的 VGG16 CNN 模型,在经过大量图像数据集进行训练后,展示了在多个图像识别任务中的卓越性能。

下面是训练模型的代码:

复制代码
 from tensorflow.keras.models import Model

    
 from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
    
 from tensorflow.keras.applications import VGG16
    
 from tensorflow.keras.preprocessing.image import ImageDataGenerator
    
  
    
 # Define the input shape of the images
    
 input_shape = (224, 224, 3)
    
  
    
 # Load the VGG16 model
    
 base_model = VGG16(weights='imagenet', include_top=False, input_shape=input_shape)
    
  
    
 # Add a global average pooling layer
    
 x = base_model.output
    
 x = GlobalAveragePooling2D()(x)
    
  
    
 # Add a fully connected layer
    
 x = Dense(128, activation='relu')(x)
    
  
    
 # Add the output layer
    
 output = Dense(1, activation='sigmoid')(x)
    
  
    
 # Define the model
    
 model = Model(inputs=base_model.input, outputs=output)
    
  
    
 # Freeze the layers of the VGG16 model
    
 for layer in base_model.layers:
    
     layer.trainable = False
    
  
    
 # Compile the model
    
 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    
  
    
 # Define the data generators for training and validation
    
 train_datagen = ImageDataGenerator(rescale=1./255,
    
                                    rotation_range=10,
    
                                    width_shift_range=0.1,
    
                                    height_shift_range=0.1,
    
                                    shear_range=0.1,
    
                                    zoom_range=0.1,
    
                                    horizontal_flip=True,
    
                                    fill_mode='nearest')
    
  
    
 val_datagen = ImageDataGenerator(rescale=1./255)
    
  
    
 train_generator = train_datagen.flow_from_directory(train_dir,
    
                                                     target_size=input_shape[:2],
    
                                                     batch_size=32,
    
                                                     class_mode='binary')
    
  
    
 val_generator = val_datagen.flow_from_directory(val_dir,
    
                                                 target_size=input_shape[:2],
    
                                                 batch_size=32,
    
                                                 class_mode='binary')
    
  
    
 # Train the model
    
 model.fit(train_generator,
    
           steps_per_epoch=len(train_generator),
    
           epochs=10,
    
           validation_data=val_generator,
    
           validation_steps=len(val_generator))

随后,我们将从 ImageNet 数据集中提取的预训练权重加载到 VGG16 模型中。此外,模型架构包含 sigmoid 激活函数的输出层、128 个神经元的全连接层以及全局平均池化层。VGG16 模型的所有层均被锁定,通过 Adam 优化器和二元交叉熵损失函数来训练该模型。随后,我们定义了数据生成器,用于训练和验证,以扩大数据集并确保像素值归一化至 [0, 1] 区间。

使用拟合方法以及训练和验证数据生成器,我们训练模型 10 个时期。

评估模型

为了考察模型在训练后的泛化性能如何,我们必须评估其在测试集上的表现。为了评估模型的性能,我们将采用数据集的测试集。此外,我们将展示分类结果的实例,包括正确和错误分类的图像。

使用下面的代码评估模型并显示一些实例。

复制代码
 import numpy as np

    
 import matplotlib.pyplot as plt
    
  
    
 # Define the path to the test directory
    
 test_dir = 'path/to/input/dir/chest_xray/test'
    
  
    
 # Define the data generator for test
    
 test_datagen = ImageDataGenerator(rescale=1./255)
    
  
    
 test_generator = test_datagen.flow_from_directory(test_dir,
    
                                                   target_size=input_shape[:2],
    
                                                   batch_size=32,
    
                                                   class_mode='binary',
    
                                                   shuffle=False)
    
  
    
 # Evaluate the model on the test set
    
 loss, accuracy = model.evaluate(test_generator, steps=len(test_generator))
    
 print(f'Test accuracy: {accuracy:.2f}')
    
  
    
 # Get the predictions and true labels
    
 predictions = model.predict(test_generator, steps=len(test_generator))
    
 predictions = np.squeeze(predictions)
    
 true_labels = test_generator.labels
    
  
    
 # Get the image filenames
    
 filenames = test_generator.filenames
    
  
    
 # Find the indices of the correctly and incorrectly classified images
    
 correct_indices = np.where((predictions >= 0.5) == true_labels)[0]
    
 incorrect_indices = np.where((predictions >= 0.5) != true_labels)[0]
    
  
    
 # Plot some correctly classified images
    
 plt.figure(figsize=(10, 10))
    
 for i, idx in enumerate(correct_indices[:9]):
    
     plt.subplot(3, 3, i+1)
    
     img = plt.imread(os.path.join(test_dir, filenames[idx]))
    
     plt.imshow(img, cmap='gray')
    
     plt.title('PNEUMONIA' if predictions[idx] >= 0.5 else 'NORMAL')
    
     plt.axis('off')
    
  
    
 # Plot some incorrectly classified images
    
 plt.figure(figsize=(10, 10))
    
 for i, idx in enumerate(incorrect_indices[:9]):
    
     plt.subplot(3, 3, i+1)
    
     img = plt.imread(os.path.join(test_dir, filenames[idx]))
    
     plt.imshow(img, cmap='gray')
    
     plt.title('PNEUMONIA' if predictions[idx] >= 0.5 else 'NORMAL')
    
     plt.axis('off')
    
  
    
 plt.show()

在该代码中,我们生成了一个用于测试和评估的数据集生成器,用于模型评估。随后,我们获取了测试集的预测结果和真实标签,并识别出正确分类和错误分类的图像索引。最后,借助Matplotlib库,我们生成了一些正确和错误分类图像的实例。

结论

在本教程中,我们构建了一个肺炎检测模型,并利用OpenCV和TensorFlow作为工具。通过OpenCV,我们实现了对图像的读取、处理和可视化。同时,我们利用TensorFlow对模型进行了训练和测试。该模型以高精度对大多数测试集的图像完成了分类任务。

计算机视觉可以充当医疗诊断的重要支持。尽管它们无法完全替代受过专业训练的医疗工作者,但它们能够显著减少诊断时间并提升诊断准确度。关于此方面的更多案例,请参阅以下链接:https://arxiv.org/pdf/2203.15269.pdf

☆ END ☆

若发现此处,表示您对本文有浓厚兴趣,请您转发并给予点赞。请通过微信搜索「uncle_pn」,并欢迎添加小编微信「 woshicver」。每天,我们的朋友圈都会更新一篇高质量的博文。

扫描二维码添加小编↓

edac2837cc4e45cfc6b7d40480e95d23.jpeg

全部评论 (0)

还没有任何评论哟~