import glob
import time
import cv2
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.metrics import confusion_matrix
from torch.utils.data import DataLoader
from tqdm import tqdm
from source.utils import *
from source.models import *
from segmentation_models.segmentation_models_pytorch.pspnet import PSPNet
from segmentation_models.segmentation_models_pytorch.deeplabv3 import DeepLabV3Plus
from segmentation_models.segmentation_models_pytorch.pspnet import PSPNet
from segmentation_models.segmentation_models_pytorch.fpn import FPN
class TongueSegDataset(torch.utils.data.Dataset):
def __init__(self, path_sampleDir, path_labelDir, transform_sample=None, transform_label=None, transform_both=None):
super().__init__()
self.transform_sample = transform_sample
self.paths_sample = glob.glob(os.path.join(path_sampleDir, '*'))
self.paths_label = []
for path_sample in self.paths_sample:
self.paths_label.append(os.path.join(path_labelDir, os.path.basename(path_sample)))
self.transform_label = transform_label
self.transform_both = transform_both
def __getitem__(self, index):
# Load sample
path_sample = self.paths_sample[index]
sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0
sample = sample.permute(2, 0, 1).float()
if self.transform_sample:
sample = self.transform_sample(sample)
# Load label
path_label = self.paths_label[index]
label = torch.from_numpy(cv2.imread(path_label, cv2.IMREAD_COLOR))
label[label <= 128] = 0.0
label[label > 128] = 1.0
label = label.permute(2, 0, 1).float()
if self.transform_label:
label = self.transform_label(label)
if self.transform_both:
for tf, p in self.transform_both:
if random.random() < p:
sample = tf(sample)
label = tf(label)
label_pos = label[0, :, :]
label_neg = torch.ones(label_pos.shape) - label[0, :, :]
label_pos = label_pos.unsqueeze(0)
label_neg = label_neg.unsqueeze(0)
label = torch.cat([label_pos, label_neg], axis=0)
return sample, label
def __len__(self):
return len(self.paths_sample)
fix_rand(2021)
# load data train
path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample")
path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label")
dataset_test = TongueSegDataset(path_testSample, path_testLabel)
data_loader_test = DataLoader(dataset_test, batch_size=1, shuffle=False)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# CHANGE THAT
shouldSave = True
model_path = r"D:\Noguchi\Solution\TongueSegmentation\result\CompareModels\FPN\bestModel.pth"
model = FPN(classes=2)
# outputpath
path_outputDir = os.path.dirname(model_path)
# model load
model.load_state_dict(torch.load(model_path))
model = model.to(device)
model.eval()
# # パラメータカウント
# params = 0
# for p in model.parameters():
# params += p.numel()
# print("params: ", params)
#
# # 推論時間計測
# since = time.perf_counter()
# for repeated in range(10):
# for i, data in enumerate(data_loader_test, 0):
# inputs = data[0].to(device)
# labels = data[1].to(device)
# outputs = model(inputs).sigmoid()
# pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0]
# ret, img_pred = cv2.threshold((pred * 255).astype(np.uint8), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# time_elapsed = (time.perf_counter() - since) / 10.0
# print("time: ", time_elapsed)
#
# with open(path_outputDir + r'/test_time¶ms.csv', 'x', encoding='utf-8') as f:
# f.write("time," + str(time_elapsed) + "\n")
# f.write("params," + str(params) + "\n")
shouldShow = True
df = pd.DataFrame()
df_refined = pd.DataFrame()
for i, data in tqdm(enumerate(data_loader_test, 0)):
name = os.path.splitext(os.path.basename(glob.glob(path_testSample + "/*")[i]))[0]
inputs = data[0].to(device)
labels = data[1].to(device)
outputs = model(inputs).sigmoid()
pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0]
true = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0]
img_pred = (pred * 255).astype(np.uint8)
# otsu
ret, img_pred = cv2.threshold(img_pred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# スコア計算
y_pred = (img_pred / 255).flatten()
y_true = true.flatten()
tn, fp, fn, tp = confusion_matrix(y_pred, y_true).ravel()
iou_tp = tp / (tp + fp + fn)
r = pd.DataFrame([name, tn, fp, fn, tp, iou_tp]).T
df = pd.concat([df, r], axis=0)
# ノイズ除去 Remove small regions
img_pred_refined = img_pred.copy()
contours = cv2.findContours(img_pred_refined, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
# 一番面積が大きい輪郭を選択する。
max_cnt = max(contours, key=lambda x: cv2.contourArea(x))
# 黒い画像に一番大きい輪郭だけ塗りつぶして描画する。
img_pred_refined = np.zeros_like(img_pred_refined)
cv2.drawContours(img_pred_refined, [max_cnt], -1, color=255, thickness=-1)
# スコア計算
y_pred_refined = (img_pred_refined / 255).flatten()
tn, fp, fn, tp = confusion_matrix(y_pred_refined, y_true).ravel()
iou_tp = tp / (tp + fp + fn)
r = pd.DataFrame([name, tn, fp, fn, tp, iou_tp]).T
df_refined = pd.concat([df_refined, r], axis=0)
if shouldSave and i >= 153:
cv2.imwrite(path_outputDir + r"/" + str(i + 1) + ".png", img_pred)
cv2.imwrite(path_outputDir + r"/" + str(i + 1) + "_refined.png", img_pred_refined)
if shouldShow and i == 153:
img_input = inputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0]
plt.imshow(img_input)
plt.show()
img_label = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0]
plt.imshow(img_label)
plt.show()
plt.imshow(img_pred)
plt.show()
plt.imshow(img_pred_refined)
plt.show()
df.columns = ["name", "tn", "fp", "fn", "tp", "iou_tp"]
mean = pd.DataFrame(df.mean(axis=0)).T
df = pd.concat([df, mean])
if shouldSave:
df.to_csv(path_outputDir + r'/Log_detail.csv', index=False)
df_refined.columns = ["name", "tn", "fp", "fn", "tp", "iou_tp"]
mean = pd.DataFrame(df_refined.mean(axis=0)).T
df_refined = pd.concat([df_refined, mean])
if shouldSave:
df_refined.to_csv(path_outputDir + r'/Log_detail_refined.csv', index=False)
print("全体平均:", df["iou_tp"].to_numpy()[-1])
print("全体平均 ノイズ除去後:", df_refined["iou_tp"].to_numpy()[-1])