Files
ai-med-edu/seminars/Тема 1.1/resource2.ipynb
T

205 lines
6.6 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "9B_sc-M_NlTZ"
},
"source": [
"Шаг 1. Устанавливаем библиотеку для работы с загрузкой данных по ссылке"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OsQErPaDDkmK",
"outputId": "49149067-e8b9-42f8-acbe-15b2d80cd79e"
},
"outputs": [],
"source": [
"!pip install gdown\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_F6Rmsu4NviH"
},
"source": [
"Шаг 3. Скачиваем и распаковываем файлы,з ная ID"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "d19wjKXOLIyw",
"outputId": "804d657b-dce7-4822-c631-b6a330801207"
},
"outputs": [],
"source": [
"import gdown\n",
"\n",
"# ID файла с Google Диска\n",
"file_id = '1qVrpV7vmhIsUxFiH189LmAn0ALbAPrgS'\n",
"#https://drive.google.com/file/d/1qVrpV7vmhIsUxFiH189LmAn0ALbAPrgS/view?usp=drive_link\n",
"# Формируем URL для скачивания\n",
"url = f'https://drive.google.com/uc?id={file_id}'\n",
"\n",
"# Скачиваем файл в директорию /content/\n",
"file_path = '/content/my_file_name.tar'\n",
"gdown.download(url, file_path, quiet=False)\n",
"\n",
"# Распаковываем архив .tar\n",
"import tarfile\n",
"with tarfile.open(file_path, 'r') as tar:\n",
" tar.extractall(path='/content/')\n",
" print(\"Архив распакован в директорию /content/\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YNJiS-a6N4vg"
},
"source": [
"Шаг 4. Просматриваем структуру и описание данных в JSON"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "_G-7skCHPJZ2",
"outputId": "f0d8712c-1805-4a5d-c857-3c6b6659fc71"
},
"outputs": [],
"source": [
"import json\n",
"\n",
"# Путь к файлу JSON\n",
"json_file_path = '/content/Task08_HepaticVessel/dataset.json'\n",
"\n",
"# Загружаем содержимое JSON файла\n",
"with open(json_file_path, 'r') as f:\n",
" dataset_info = json.load(f)\n",
"\n",
"# Просмотрим содержимое JSON\n",
"print(json.dumps(dataset_info, indent=4)) # Красиво выводим содержимое\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4GOfTVYdODLL"
},
"source": [
"Шаг 5. Выводим для просмотра 20 случайных объектов с метками из обучающего набора."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
},
"id": "CTMaymbpP1IQ",
"outputId": "e6ce5b6a-b949-4499-93e5-a7f8816bc888"
},
"outputs": [],
"source": [
"import random\n",
"import nibabel as nib\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import os\n",
"\n",
"# Папки с изображениями и метками\n",
"images_dir = '/content/Task08_HepaticVessel/imagesTr'\n",
"labels_dir = '/content/Task08_HepaticVessel/labelsTr'\n",
"\n",
"# Фильтруем доступные файлы\n",
"available_files = sorted([f for f in os.listdir(images_dir) if not f.startswith('._') and f.endswith('.nii.gz')])\n",
"images = [os.path.join(images_dir, file) for file in available_files]\n",
"labels = [os.path.join(labels_dir, file.replace('imagesTr', 'labelsTr')) for file in available_files]\n",
"\n",
"# Проверяем количество файлов\n",
"print(f\"Обнаружено {len(images)} изображений и {len(labels)} меток.\")\n",
"\n",
"# Случайно выбираем 20 изображений\n",
"random_indices = random.sample(range(len(images)), min(20, len(images)))\n",
"\n",
"# Цветовая карта для меток\n",
"cmap = plt.cm.colors.ListedColormap(['black', 'green', 'red']) # Цвета: фон, сосуды, опухоли\n",
"bounds = [0, 1, 2, 3]\n",
"norm = plt.cm.colors.BoundaryNorm(bounds, cmap.N)\n",
"\n",
"# Визуализация изображений и меток\n",
"for idx in random_indices:\n",
" try:\n",
" # Загружаем изображение и метку\n",
" image = nib.load(images[idx]).get_fdata()\n",
" label = nib.load(labels[idx]).get_fdata()\n",
"\n",
" # Поиск срезов с ненулевыми метками\n",
" non_empty_slices = [z for z in range(label.shape[2]) if np.unique(label[:, :, z]).size > 1]\n",
"\n",
" if not non_empty_slices:\n",
" print(f\"Все срезы в {images[idx]} содержат только фон.\")\n",
" continue\n",
"\n",
" # Выбираем случайный срез с ненулевыми метками\n",
" slice_index = random.choice(non_empty_slices)\n",
" print(f\"Выбран срез {slice_index} для изображения {images[idx]}\")\n",
"\n",
" plt.figure(figsize=(10, 5))\n",
"\n",
" # Отображаем изображение\n",
" plt.subplot(1, 2, 1)\n",
" plt.imshow(image[:, :, slice_index], cmap='gray')\n",
" plt.title(f'Изображение (Slice: {slice_index})')\n",
" plt.axis('off')\n",
"\n",
" # Отображаем метки\n",
" plt.subplot(1, 2, 2)\n",
" plt.imshow(label[:, :, slice_index], cmap=cmap, norm=norm)\n",
" plt.title('Метки')\n",
" plt.axis('off')\n",
"\n",
" plt.show()\n",
"\n",
" except Exception as e:\n",
" print(f\"Ошибка при обработке файла {images[idx]}: {e}\")\n"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"gpuType": "T4",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}