atom-predict/msunet/.ipynb_checkpoints/DataPreProcess-checkpoint.i...

218 lines
6.2 KiB
Plaintext
Executable File

{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "66ee10ca-9a42-4e52-a56c-3c4e8b470afa",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import cv2\n",
"import glob\n",
"import copy\n",
"import json\n",
"import shutil\n",
"import numpy as np\n",
"import pandas as pd\n",
"import seaborn as sns\n",
"import matplotlib.pyplot as plt\n",
"\n",
"from PIL import Image\n",
"from labelme import utils\n",
"from skimage.feature import peak_local_max"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "40711569-6f55-49d2-8a88-152c7b677218",
"metadata": {},
"outputs": [],
"source": [
"class_dict = {\n",
" 1: 'Norm', \n",
" 2: 'SV',\n",
" 3: 'LineSV',\n",
"}\n",
"\n",
"class_dict_rev = {\n",
" 'Norm': 1, \n",
" 'SV': 2,\n",
" 'LineSV': 3,\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "1762751c-7d19-482c-96ff-477b9ea50e5b",
"metadata": {},
"outputs": [],
"source": [
"def crop_slide(img_path, save_path, patch_size=256, step=128):\n",
" base_name = img_path.split('/')[-1].split('.')[0]\n",
" json_path = img_path.replace('.jpg', '.json')\n",
" img = cv2.imread(img_path, 0)\n",
" # img = cv2.equalizeHist(img)\n",
" # img = cv2.GaussianBlur(img, (5, 5), 0)\n",
" h, w = img.shape\n",
" \n",
" with open(json_path) as f:\n",
" json_data = json.load(f)\n",
"\n",
" points = np.array([item['points'][0][::-1] for item in json_data['shapes']], np.int32)\n",
" labels = np.array([class_dict_rev[item['label']] for item in json_data['shapes']], np.int32)\n",
" \n",
" mask = np.zeros_like(img)\n",
" mask[points[:, 0], points[:, 1]] = labels\n",
"\n",
" for i in range(0, h-patch_size+1, step):\n",
" for j in range(0, w-patch_size+1, step):\n",
" v_nums = np.sum(mask[i:i+patch_size, j:j+patch_size] > 1)\n",
" \n",
" Image.fromarray(img[i:i+patch_size, j:j+patch_size]).save(\n",
" os.path.join(save_path, 'img', '{}_{}_{}_{}.png'.format(base_name, str(i), str(j), str(v_nums)))\n",
" )\n",
" \n",
" Image.fromarray(mask[i:i+patch_size, j:j+patch_size]).save(\n",
" os.path.join(save_path, 'lbl', '{}_{}_{}_{}.png'.format(base_name, str(i), str(j), str(v_nums)))\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "1417b046-4e1c-4b9c-9aff-cf5295701601",
"metadata": {},
"outputs": [],
"source": [
"def process_slide(img_path, save_path):\n",
" base_name = img_path.split('/')[-1].split('.')[0]\n",
" json_path = img_path.replace('.jpg', '.json')\n",
" img = cv2.imread(img_path, 0)\n",
" # img = cv2.equalizeHist(img)\n",
" # img = cv2.GaussianBlur(img, (5, 5), 0)\n",
" \n",
" h, w = img.shape\n",
" \n",
" with open(json_path) as f:\n",
" json_data = json.load(f)\n",
"\n",
" points = np.array([item['points'][0][::-1] for item in json_data['shapes']], np.int32)\n",
" labels = np.array([class_dict_rev[item['label']] for item in json_data['shapes']], np.int32)\n",
" \n",
" # mask = np.zeros_like(img)\n",
" # for idx, point in enumerate(points):\n",
" # cv2.circle(mask, point[::-1], 8, int(labels[idx]), -1)\n",
" \n",
" mask = np.zeros_like(img)\n",
" mask[points[:, 0], points[:, 1]] = labels\n",
" \n",
" Image.fromarray(img).save(\n",
" os.path.join(save_path, 'img', '{}.png'.format(base_name))\n",
" )\n",
" \n",
" Image.fromarray(mask).save(\n",
" os.path.join(save_path, 'lbl', '{}.png'.format(base_name))\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "59c532e0-39ec-406c-8d77-e0a17a9181cd",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"img_lst = glob.glob('../../data/linesv/slide/*.jpg') \n",
"img_lst.sort(); len(img_lst)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "41c0bdb9-f5ca-4744-bc8a-d5d9723716c9",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"for _type in ['train', 'valid', 'test']: \n",
" os.makedirs('../../data/linesv/patch_unet/{}/img'.format(_type), exist_ok=True)\n",
" os.makedirs('../../data/linesv/patch_unet/{}/lbl'.format(_type), exist_ok=True)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "378409b3-66b2-4325-8822-104c9c2519a1",
"metadata": {},
"outputs": [],
"source": [
"crop_slide('../../data/linesv/slide/0.jpg', save_path='../../data/linesv/patch_unet/train/', step=64)\n",
"crop_slide('../../data/linesv/slide/3.jpg', save_path='../../data/linesv/patch_unet/valid/', step=256)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "14d437d6-a43c-4471-a5ff-5df43e273819",
"metadata": {},
"outputs": [],
"source": [
"for name in [2, 4, 6, 8, 10, 20, 30, 40]:\n",
" process_slide('../../data/linesv/slide/{}.jpg'.format(name), save_path='../../data/linesv/patch_unet/test/')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ecdb4f79-cfa5-4511-bf67-21bbe26ba403",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "ee0f80af-0c81-43fc-b879-002ad63413e8",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "cmae",
"language": "python",
"name": "cmae"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.16"
}
},
"nbformat": 4,
"nbformat_minor": 5
}