肺癌の画像診断AIプログラム

 以下に、肺癌の画像診断AIのプログラムをPythonのTkinterを使用してGUIで実装したサンプルコードを示します。このプログラムは、CTスキャン画像を入力として受け取り、肺癌の有無を判定するシンプルなモデルを使用します。モデルのトレーニングや詳細な画像処理は省略していますが、GUIの構築と基本的な機能を示します。


```python

import tkinter as tk

from tkinter import filedialog, messagebox

from PIL import Image, ImageTk

import numpy as np

from tensorflow.keras.models import load_model


# 事前にトレーニング済みのモデルをロード

model = load_model('lung_cancer_model.h5')


def load_image():

    file_path = filedialog.askopenfilename()

    if file_path:

        image = Image.open(file_path)

        image = image.resize((224, 224))  # モデルの入力サイズに合わせる

        image = ImageTk.PhotoImage(image)

        image_label.config(image=image)

        image_label.image = image

        return np.array(image) / 255.0  # 正規化

    return None


def predict_image(image_array):

    if image_array is not None:

        image_array = np.expand_dims(image_array, axis=0)  # バッチ次元を追加

        prediction = model.predict(image_array)

        if prediction[0] > 0.5:

            messagebox.showinfo("Prediction", "Lung cancer detected.")

        else:

            messagebox.showinfo("Prediction", "No lung cancer detected.")

    else:

        messagebox.showwarning("Warning", "Please load an image first.")


# GUIの設定

root = tk.Tk()

root.title("Lung Cancer Detection AI")

root.geometry("600x400")


# ウィジェットの配置

load_button = tk.Button(root, text="Load Image", command=load_image)

load_button.pack(pady=20)


image_label = tk.Label(root)

image_label.pack(pady=20)


predict_button = tk.Button(root, text="Predict", command=lambda: predict_image(load_image()))

predict_button.pack(pady=20)


root.mainloop()

```


### 説明


1. **ライブラリのインポート**:

   - `tkinter`: GUIの作成に使用。

   - `filedialog`: ファイルダイアログの表示。

   - `messagebox`: メッセージボックスの表示。

   - `PIL`: 画像の読み込みと表示。

   - `numpy`: 画像データの前処理。

   - `tensorflow`: モデルのロードと予測。


2. **モデルのロード**:

   - `load_model('lung_cancer_model.h5')`: 事前にトレーニング済みのモデルをロード。


3. **画像の読み込み**:

   - `load_image()`: ファイルダイアログを表示し、選択した画像を読み込み、表示する。


4. **予測**:

   - `predict_image(image_array)`: 画像データをモデルに入力し、予測結果を表示。


5. **GUIの設定**:

   - `tk.Tk()`: GUIアプリケーションのインスタンスを作成。

   - `load_button`: 画像を読み込むボタン。

   - `image_label`: 画像を表示するラベル。

   - `predict_button`: 予測を実行するボタン。


このプログラムは、基本的なGUIを提供し、ユーザーがCTスキャン画像を読み込み、肺癌の有無を予測することができます。実際の使用には、モデルのトレーニングやデータの前処理が必要です。


19 Citations


Python GUI Programming: Your Tkinter Tutorial – Real Python

https://realpython.com/python-gui-tkinter/


Official GUI Builder for Tkinter - Python Help - Discussions on Python.org

https://discuss.python.org/t/official-gui-builder-for-tkinter/86498


Lung Cancer Detection using Convolutional Neural Network (CNN) | GeeksforGeeks

https://www.geeksforgeeks.org/lung-cancer-detection-using-convolutional-neural-network-cnn/


Create Python GUI with Tkinter

https://www.pythonguis.com/tutorials/create-gui-tkinter/


Explainable AI for lung cancer detection via a custom CNN on CT images | Scientific Reports

https://www.nature.com/articles/s41598-025-97645-5


Efficient Image Labeling with Python and Tkinter: A Guide to Simplifying Dataset Preparation for AI - DEV Community

https://dev.to/imankarimi/efficient-image-labeling-with-python-and-tkinter-a-guide-to-simplifying-dataset-preparation-for-ai-24od


How To Build GUI In Python - Step By Step Guide

https://zencoder.ai/blog/build-gui-in-python


Text detection using Python - GeeksforGeeks

https://www.geeksforgeeks.org/python/text-detection-using-python/


How to Install Tkinter in Python

https://updategadh.com/python-interview-question/how-to-install-tkinter-in-python/


A robust deep learning algorithm for lung cancer detection from computed tomography images - ScienceDirect

https://www.sciencedirect.com/science/article/pii/S2666521225000067


How I Built A Blood Pressure Tracker With Python, Tkinter, And Matplotlib - Kreezcraft

https://kreezcraft.com/how-i-built-a-blood-pressure-tracker-with-python-tkinter-and-matplotlib/


Browse Upload & Display Image in Tkinter - GeeksforGeeks

https://www.geeksforgeeks.org/python/browse-upload-display-image-in-tkinter/


Image Processing in Python: Algorithms, Tools, and Methods You Should Know

https://neptune.ai/blog/image-processing-python


Deep learning-based approach to diagnose lung cancer using CT-scan images - ScienceDirect

https://www.sciencedirect.com/science/article/pii/S2666521224000553


Top 4 Pre-Trained Models for Image Classification with Python Code

https://www.analyticsvidhya.com/blog/2020/08/top-4-pre-trained-models-for-image-classification-with-python-code/


[2506.07236] A Narrative Review on Large AI Models in Lung Cancer Screening, Diagnosis, and Treatment Planning

https://arxiv.org/abs/2506.07236


Imaging-aided diagnosis and treatment based on artificial intelligence for pulmonary nodules: A review - ScienceDirect

https://www.sciencedirect.com/science/article/abs/pii/S1120179725001607


Build an Image-to-Text Converter Using Python

https://citrusbug.com/blog/build-image-to-text-converter-using-python/


Machine Learning Lung Cancer Detection using CNN - Project Gurukul

https://projectgurukul.org/ml-lung-cancer-detection/


肺癌の画像診断AIを構築するためのデータセットは、LIDC-IDRI(Lung Image Database Consortium and Image Database Resource Initiative)データセットがよく使用されます。このデータセットは、胸部CTスキャンの画像と、それらの画像に含まれる病変(特に肺結節)の注釈を提供しています。LIDC-IDRIデータセットは、アメリカ国家癌症研究所(NCI)が主導し、複数の医療機関と大学が協力して作成したもので、1018の病例から成り立っています^1,2^データセットの詳細な情報やダウンロード方法については、The Cancer Imaging Archive(TCIA)の公式ウェブサイトから確認できます^1^


次に、LIDC-IDRIデータセットをダウンロードし、前処理とトレーニングを行うためのPythonプログラムを示します。このプログラムは、データのダウンロード、前処理、モデルのトレーニング、そして評価を行います。


### 1. データセットのダウンロード


LIDC-IDRIデータセットをダウンロードするためには、TCIAのウェブサイトからデータセットを選択し、必要な情報を入力してダウンロードリクエストを送信します。以下は、Pythonを使用してデータセットをダウンロードするためのスクリプトの例です。


```python

import os

import requests

from tqdm import tqdm


# TCIA APIエンドポイント

API_ENDPOINT = "https://services.cancerimagingarchive.net/services/getImageCollection"


# LIDC-IDRIのコレクションID

COLLECTION_ID = "LIDC-IDRI"


# ダウンロード先のディレクトリ

DOWNLOAD_DIR = "LIDC-IDRI"


# ダウンロードリクエストのパラメータ

params = {

    "collection": COLLECTION_ID,

    "api_key": "YOUR_API_KEY"  # TCIAから取得したAPIキー

}


# 画像のメタデータを取得

response = requests.get(API_ENDPOINT, params=params)

image_metadata = response.json()


# 画像ファイルのダウンロード

for image in tqdm(image_metadata["images"], desc="Downloading images"):

    image_id = image["image_id"]

    image_url = image["image_url"]

    local_path = os.path.join(DOWNLOAD_DIR, f"{image_id}.dcm")


    if not os.path.exists(local_path):

        os.makedirs(DOWNLOAD_DIR, exist_ok=True)

        with requests.get(image_url, stream=True) as r:

            r.raise_for_status()

            with open(local_path, 'wb') as f:

                for chunk in r.iter_content(chunk_size=8192):

                    f.write(chunk)

```


### 2. データの前処理


ダウンロードしたDICOM画像を前処理します。ここでは、画像の読み込み、リサイズ、正規化を行います。


```python

import pydicom

import numpy as np

from skimage.transform import resize

from sklearn.model_selection import train_test_split


def preprocess_image(image_path):

    # DICOM画像を読み込む

    dicom = pydicom.dcmread(image_path)

    image = dicom.pixel_array


    # 画像のリサイズと正規化

    image = resize(image, (224, 224), anti_aliasing=True)

    image = image / np.max(image)


    return image


# 前処理された画像とラベルのリスト

images = []

labels = []


for image_path in os.listdir(DOWNLOAD_DIR):

    if image_path.endswith(".dcm"):

        image = preprocess_image(os.path.join(DOWNLOAD_DIR, image_path))

        label = 1 if "cancer" in image_path else 0  # ここではファイル名に"cancer"が含まれている場合を癌と仮定

        images.append(image)

        labels.append(label)


# 訓練データと検証データに分割

X_train, X_val, y_train, y_val = train_test_split(images, labels, test_size=0.2, random_state=42)

```


### 3. モデルのトレーニング


前処理されたデータを使用して、CNNモデルをトレーニングします。


```python

import tensorflow as tf

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout

from tensorflow.keras.optimizers import Adam


# モデルの構築

model = Sequential([

    Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 1)),

    MaxPooling2D((2, 2)),

    Conv2D(64, (3, 3), activation='relu'),

    MaxPooling2D((2, 2)),

    Flatten(),

    Dense(128, activation='relu'),

    Dropout(0.5),

    Dense(1, activation='sigmoid')

])


# モデルのコンパイル

model.compile(optimizer=Adam(learning_rate=0.001), loss='binary_crossentropy', metrics=['accuracy'])


# モデルのトレーニング

history = model.fit(np.array(X_train), np.array(y_train), epochs=20, batch_size=32, validation_data=(np.array(X_val), np.array(y_val)))

```


### 4. モデルの評価


トレーニングが完了したら、検証データセットを使用してモデルの性能を評価します。


```python

# モデルの評価

loss, accuracy = model.evaluate(np.array(X_val), np.array(y_val))

print(f"Validation Accuracy: {accuracy * 100:.2f}%")

```


### 5. GUIの実装


Tkinterを使用して、ユーザーが画像を読み込み、モデルで予測を行うGUIを作成します。


```python

import tkinter as tk

from tkinter import filedialog, messagebox

from PIL import Image, ImageTk

import numpy as np


def load_image():

    file_path = filedialog.askopenfilename()

    if file_path:

        image = Image.open(file_path)

        image = image.resize((224, 224))  # モデルの入力サイズに合わせる

        image = ImageTk.PhotoImage(image)

        image_label.config(image=image)

        image_label.image = image

        return np.array(image) / 255.0  # 正規化

    return None


def predict_image(image_array):

    if image_array is not None:

        image_array = np.expand_dims(image_array, axis=0)  # バッチ次元を追加

        prediction = model.predict(image_array)

        if prediction[0] > 0.5:

            messagebox.showinfo("Prediction", "Lung cancer detected.")

        else:

            messagebox.showinfo("Prediction", "No lung cancer detected.")

    else:

        messagebox.showwarning("Warning", "Please load an image first.")


# GUIの設定

root = tk.Tk()

root.title("Lung Cancer Detection AI")

root.geometry("600x400")


# ウィジェットの配置

load_button = tk.Button(root, text="Load Image", command=load_image)

load_button.pack(pady=20)


image_label = tk.Label(root)

image_label.pack(pady=20)


predict_button = tk.Button(root, text="Predict", command=lambda: predict_image(load_image()))

predict_button.pack(pady=20)


root.mainloop()

```


このプログラムは、LIDC-IDRIデータセットをダウンロードし、前処理を行い、CNNモデルをトレーニングして、Tkinterを使用してGUIを実装しています。これにより、ユーザーは画像を読み込み、肺癌の有無を予測することができます。


2 Citations


LIDC-IDRI - The Cancer Imaging Archive (TCIA)

https://www.cancerimagingarchive.net/collection/lidc-idri/


LIDC-IDRI|医学影像数据集|肺部疾病诊断数据集

https://www.selectdataset.com/dataset/0ff597491ea5e5d414293d413f49a197

コメント

このブログの人気の投稿

ミライアイ内服薬は薬事法違反で、ほとんど効果がない詐欺ですか?

最高裁での上告理由書受理・却下の判断基準について

裁判官の忌避申立書の作成例