diff --git a/contrib/PraNetSegmentation/README.md b/contrib/PraNetSegmentation/README.md index ac9fda329e8272f0098d3a5a41918fb694927cff..2c2aa29cfa0f51e8a13eafade40f85dff038eed8 100644 --- a/contrib/PraNetSegmentation/README.md +++ b/contrib/PraNetSegmentation/README.md @@ -1,154 +1,69 @@ -# PraNet SDK开发样例 +# PraNet医学分割 ## 1 介绍 +### 1.1 简介 + PraNet是一种针对息肉分割任务需求设计的,名为并行反向注意力的深度神经网络。 基于并行反向注意力的息肉分割网络(PraNet),利用并行的部分解码器(PPD)在高级层中聚合特征作为初始引导区域, 再使用反向注意模块(RA)挖掘边界线索。 本项目基于Mind SDK框架实现了PraNet模型的推理。 -### 1.1 支持的产品 - -Ascend 310 - -### 1.2 支持的版本 +### 1.2 支持的产品 +Atlas 300I pro、Atlas 300V pro -CANN:7.0.RC1 +### 1.3 支持的版本 +本样例配套的MxVision版本、CANN版本、Driver/Firmware版本如下所示: +| MxVision版本 | CANN版本 | Driver/Firmware版本 | +| --------- | ------------------ | -------------- | +| 6.0.RC3 | 8.0.RC3 | 24.1.RC3 | -SDK:mxVision 5.0.RC3(可通过cat SDK目录下的 version.info 查看) +### 1.4 三方依赖 -### 1.3 代码目录结构与说明 +第三方依赖软件和版本如下表。请确认环境已安装pip3后,使用pip3 install * 安装以下依赖。 -工程目录如下图所示: +|软件名称 | 版本 | +|-----------|----------| +| numpy | 1.24.0 | +| tqdm | 4.66.5 | +| imageio | 2.36.0 | -``` -|-- pipeline -| |-- pranet_pipeline.json // SDK的推理pipeline配置文件 -|-- plugin -| |-- postprocess -| |-- build.sh // 编译脚本 -| |-- CMakeLists.txt // CMakeLists -| |-- Postprocess.cpp // 插件.cpp文件 -| |-- Postprocess.h // 插件.h文件 -|-- model -| |-- pranet.aippconfig // aippconfig -| |-- onnx2om.sh // 模型转换脚本 -|-- main.py // 实现推理功能的脚本 -|-- test_metric.py // 测试模型精度的脚本 -|-- README.md // 自述文件 -``` - -### 1.4 技术实现流程图 - -本项目首先通过onnx软件将pytorch的预训练模型转化为onnx模型,然后在使用atc工具将其转化为SDK能使用的om模型。最终通过构建SDK推理pipeline,实现模型推理。 - -### 1.5 特性及适用场景 +### 1.5 相关约束 在医疗图像处理领域,PraNet针对息肉识别需求而设计。Pranet网络能够对息肉图片进行语义分割,功能正常,且精度达标。但是在以下情况下,分割效果不够理想: 1、当息肉相比整张图片面积很小时,分割效果不够理想,边缘会比较模糊。 -2、当息肉大面具处于整张图片的边缘时,有一定概率分割失败,效果较差。(测试用例3.1.2) - -轻微的精度损失: +2、当息肉大面具处于整张图片的边缘时,有一定概率分割失败,效果较差。 -该模型相比于原模型精度稍有下降,这是因为mindsdk只提供了jpg格式图片的解码,而原数据集中的图片为png格式,所以为了将模型迁移到mindsdk,需要将数据全部转换为jpg格式。而jpg格式压缩图片是有损失的,所以造成了一定的精度下降。 - -## 2 环境依赖 - -推荐系统为ubuntu 18.04,环境依赖软件和版本如下表: - -| 软件名称 | 版本 | 说明 | 获取方式 | -| ------------------- | ----------- | ----------------------------- | ------------------------------------------------------------ | -| MindX SDK | 5.0.RC3 | mxVision软件包 | [链接](https://gitee.com/link?target=https%3A%2F%2Fwww.hiascend.com%2Fsoftware%2FMindx-sdk) | -| ubuntu | 18.04.1 LTS | 操作系统 | Ubuntu官网获取 | -| Ascend-CANN-toolkit | 7.0.RC1 | Ascend-cann-toolkit开发套件包 | [链接](https://gitee.com/link?target=https%3A%2F%2Fwww.hiascend.com%2Fsoftware%2Fcann%2Fcommercial) | -| python | 3.9.2 | | | -| numpy | 1.22.4 | 维度数组运算依赖库 | 服务器中使用pip或conda安装 | -| opencv-python | 4.5.5.64 | 图像处理依赖库 | 服务器中使用pip或conda安装 | -| PIL | 9.0.1 | 图像处理依赖库 | 服务器中使用pip或conda安装 | -| onnx | 1.12.0 | 模型转化库 | 服务器中使用pip或conda安装 | -| tabulate | 0.8.10 | 格式化输出 | 服务器中使用pip或conda安装 | - - -键入 - -```bash -source ${SDK−path}/set_env.sh -source ${ascend-toolkit-path}/set_env.sh +## 2 设置环境变量 ``` - -以激活环境,其中```SDK-path```是SDK mxVision安装路径,```ascend-toolkit-path```是CANN安装路径。 - -## 3 准备工作 - -### 3.1 获取OM模型文件 - -OM权重文件下载参考华为昇腾社区[ModelZoo](https://www.hiascend.com/zh/software/modelzoo/models/detail/1/e08e0552334ec81d8e632fafbb22a9f0) -获取到```PraNet-19.onnx```模型后,将其放在model目录下。在model目录键入以下命令 - -``` -bash onnx2om.sh +. /usr/local/Ascend/ascend-toolkit/set_env.sh #CANN默认安装路径,根据实际安装路径修改 +. ${SDK_INSTALL_PATH}/mxVision/set_env.sh #根据实际SDK安装路径修改 ``` -能获得```PraNet-19_bs1.om```模型文件。 - -注: [ModelZoo](https://www.hiascend.com/zh/software/modelzoo/models/detail/1/e08e0552334ec81d8e632fafbb22a9f0) -中的模型文件```PraNet-19_bs1.om```不能用于本项目。 - -### 3.2 编译插件 +## 3 准备模型 -首先进入文件夹```plugin/postprocess/```,键入```bash build.sh```,对后处理插件进行编译。 - -### 3.3 下载数据集 - -数据集下载地址: -https://drive.google.com/file/d/1o8OfBvYE6K-EpDyvzsmMPndnUMwb540R/view - -本模型使用Kvasir的验证集。请用户需自行获取Kvasir数据集,上传数据集到项目根目录并解压(如:/root/datasets)。 +**步骤1:** 下载PraNet原始模型:[下载地址](https://mindx.sdk.obs.cn-north-4.myhuaweicloud.com/mindxsdk-referenceapps%20/contrib/PranetSegementation/ATC%20PraNet%28FP16%29%20from%20Pytorch%20-%20Ascend310.zip),并将获取到的PraNet-19.onnx文件存放至本案例代码的PraNetSegmentation/model目录下。 +**步骤2:** 进入PraNetSegmentation/model目录执行以下命令: ``` -TestDataset -├── Kvasir - ├── images - ├── masks +atc --model=PraNet-19.onnx --output=./PraNet-19_bs1 --framework=5 --input_shape="actual_input_1:1,3,352,352" --soc_version=Ascend310P3 --input_format=NCHW --output_type=FP32 --insert_op_conf=./pranet.aippconfig ``` +## 4 编译与运行 -## 4 SDK推理 - -在项目根目录下键入 - -```bash -python main.py --pipeline_path pipeline/pranet_pipeline.json --data_path ./TestDataset/Kvasir/images/ +**步骤1:** 编译后处理插件so:进入PraNetSegmentation/plugin/postprocess/目录,执行命令: ``` - -其中参数``` --pipeline_path ```为pipeline配置文件的路径,项目中已经给出该文件,所以直接使用相对路径即可; -``` --data_path ```参数为推理图片的路径。最终用户可以在```./infer_result/```路径下查看结果。 - -## 5 测试精度 - -在项目根目录下键入 - -```bash -python test_metric.py --pipeline_path pipeline/pranet_pipeline.json --data_path ./TestDataset/Kvasir/ +bash build.sh ``` -其中参数```--pipeline_path```为pipeline配置文件的路径,项目中已经给出该文件,所以直接使用相对路径即可; -```--data_path```参数为数据集的路径。待脚本运行完毕,会输出以下精度信息。 +**步骤2:** 准备输入图片路径:输入图片命名为test.jpg放入根目录。 -``` -dataset meanDic meanIoU ---------- --------- --------- -res 0.890 0.828 -``` - -原模型的精度为: +**步骤3:** 运行:在根目录下执行 ``` -dataset meanDic meanIoU ---------- --------- --------- -res 0.895 0.836 +python3 main.py ``` - -精度符合要求。 + +**步骤4:** 查看结果:在infer_result目录可以查看图片结果。 diff --git a/contrib/PraNetSegmentation/main.py b/contrib/PraNetSegmentation/main.py index f1d83b04e2b27c41a45abc1583312f6ba6467c8b..19897d1b6cc3910a75e06717686201cefd5e8ec5 100644 --- a/contrib/PraNetSegmentation/main.py +++ b/contrib/PraNetSegmentation/main.py @@ -64,19 +64,11 @@ def rgb_loader(path): if __name__ == '__main__': - - parser = ArgumentParser() - parser.add_argument('--pipeline_path', type=str, - default="pipeline/pranet_pipeline.json") - parser.add_argument('--data_path', type=str) - config = parser.parse_args() - INFER_RESULT = "infer_result/" if not os.path.exists(INFER_RESULT): os.mkdir(INFER_RESULT) - pipeline_path = config.pipeline_path - data_path = config.data_path + pipeline_path = "pipeline/pranet_pipeline.json" streamManagerApi = StreamManagerApi() ret = streamManagerApi.InitManager() @@ -94,16 +86,5 @@ if __name__ == '__main__': print("Failed to create Stream, ret=%s" % str(ret)) sys.exit() - if len(os.listdir(data_path)) == 0: - raise RuntimeError("No Input Image!") - - for index, data in tqdm(enumerate(sorted(os.listdir(data_path)))): - image_path = os.path.join(data_path, data) - - print("====", image_path) - infer(image_path, streamManagerApi) - - while True: # 轮询, 等待异步线程 - if os.path.exists(INFER_RESULT + str(index) + ".png"): - break + infer("./test.jpg", streamManagerApi) streamManagerApi.DestroyAllStreams() diff --git a/contrib/PraNetSegmentation/model/onnx2om.sh b/contrib/PraNetSegmentation/model/onnx2om.sh deleted file mode 100644 index 00b33b048dd412e51b6509fbfef0ddee5971620b..0000000000000000000000000000000000000000 --- a/contrib/PraNetSegmentation/model/onnx2om.sh +++ /dev/null @@ -1,7 +0,0 @@ -#! /bin/bash -atc --model=PraNet-19.onnx --output=./PraNet-19_bs1 --framework=5 \ - --input_shape="actual_input_1:1,3,352,352" \ - --soc_version=Ascend310 \ - --input_format=NCHW \ - --output_type=FP32 \ - --insert_op_conf=./pranet.aippconfig \ No newline at end of file diff --git a/contrib/PraNetSegmentation/plugin/postprocess/CMakeLists.txt b/contrib/PraNetSegmentation/plugin/postprocess/CMakeLists.txt index ac38f047998dda82efe5c16a1a8ff8eafd3fcf24..b50daef324a0ac9191560f8719670c73353df445 100644 --- a/contrib/PraNetSegmentation/plugin/postprocess/CMakeLists.txt +++ b/contrib/PraNetSegmentation/plugin/postprocess/CMakeLists.txt @@ -30,7 +30,7 @@ include_directories( link_directories(${MX_SDK_HOME}/lib) link_directories(${MX_SDK_HOME}/opensource/lib) -add_compile_options(-std=c++11 -fPIC -fstack-protector-all -pie -Wno-deprecated-declarations) +add_compile_options(-std=c++14 -fPIC -fstack-protector-all -pie -Wno-deprecated-declarations) add_compile_options("-DPLUGIN_NAME=${PLUGIN_NAME}") add_definitions(-DENABLE_DVPP_INTERFACE) diff --git a/contrib/PraNetSegmentation/test_metric.py b/contrib/PraNetSegmentation/test_metric.py deleted file mode 100644 index c7afff654cb1112cc77bfb2a76f081cc5e027d28..0000000000000000000000000000000000000000 --- a/contrib/PraNetSegmentation/test_metric.py +++ /dev/null @@ -1,406 +0,0 @@ -# Copyright (c) 2022. Huawei Technologies Co., Ltd -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os -import time -import sys -import json -from argparse import ArgumentParser -import cv2 -import numpy as np -import PIL -from PIL import Image -from StreamManagerApi import StreamManagerApi -from tqdm import tqdm -from tabulate import tabulate -from scipy.ndimage.morphology import distance_transform_edt -from scipy.ndimage.filters import convolve -import imageio - -from main import infer, resize - - -def object_(pred, gting__): - xing = np.mean(pred[gting__ == 1]) - sigma_x = np.std(pred[gting__ == 1]) - score = 2.0 * xing / (xing ** 2 + 1 + sigma_x + np.finfo(np.float64).eps) - - return score - - -def s_object(pred, gting_): - pred_fg = pred.copy() - pred_fg[gting_ != 1] = 0.0 - oing_fg = object_(pred_fg, gting_) - - pred_bg = (1 - pred.copy()) - pred_bg[gting_ == 1] = 0.0 - oing_bg = object_(pred_bg, 1-gting_) - - uing = np.mean(gting_) - qing = uing * oing_fg + (1 - uing) * oing_bg - - return qing - - -def centroid(gting_1): - if np.sum(gting_1) == 0: - return gting_1.shape[0] // 2, gting_1.shape[1] // 2 - xing, ying = np.where(gting_1 == 1) - return int(np.mean(xing).round()), int(np.mean(ying).round()) - - -def divide(gting_2, xing, ying): - l_t = gting_2[:xing, :ying] - r_t = gting_2[xing:, :ying] - l_b = gting_2[:xing, ying:] - r_b = gting_2[xing:, ying:] - - wing1 = l_t.size / gting_2.size - wing2 = r_t.size / gting_2.size - wing3 = l_b.size / gting_2.size - wing4 = r_b.size / gting_2.size - - return [l_t, r_t, l_b, r_b, wing1, wing2, wing3, wing4] - - -def ssim(pred, gting_4): - xing = np.mean(pred) - ying = np.mean(gting_4) - ning_ = pred.size - - sigma_x2 = np.sum((pred - xing) ** 2 / - (ning_ - 1 + np.finfo(np.float64).eps)) - sigma_y2 = np.sum((gting_4 - ying) ** 2 / - (ning_ - 1 + np.finfo(np.float64).eps)) - - sigma_xy = np.sum((pred - xing) * (gting_4 - ying) / - (ning_ - 1 + np.finfo(np.float64).eps)) - - alpha = 4 * xing * ying * sigma_xy - beta = (xing ** 2 + ying ** 2) * (sigma_x2 + sigma_y2) - - if alpha != 0: - qing = alpha / (beta + np.finfo(np.float64).eps) - elif alpha == 0 and beta == 0: - qing = 1 - else: - qing = 0 - - return qing - - -def s_region(pred, gting_5): - xing, ying = centroid(gting_5) - gt1, gt2, gt3, gt4, wing1, wing2, wing3, wing4 = divide( - gting_5, xing, ying) - pred1, pred2, pred3, pred4, _, _, _, _ = divide(pred, xing, ying) - - qing1 = ssim(pred1, gt1) - qing2 = ssim(pred2, gt2) - qing3 = ssim(pred3, gt3) - qing4 = ssim(pred4, gt4) - - qing = qing1 * wing1 + qing2 * wing2 + qing3 * wing3 + qing4 * wing4 - - return qing - - -def structure_measure(pred, gting_44): - ying = np.mean(gting_44) - - if ying == 0: - xing = np.mean(pred) - qing = 1 - xing - elif ying == 1: - xing = np.mean(pred) - qing = xing - else: - alpha = 0.5 - qing = alpha * s_object(pred, gting_44) + \ - (1 - alpha) * s_region(pred, gting_44) - qing = max(qing, 0) - - return qing - - -def fspecial_gauss(size, sigma): - """Function to mimic the 'fspecial' gaussian MATLAB function - """ - xing, ying = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] - g_1 = np.exp(-((xing**2 + ying**2)/(2.0*sigma**2))) - return g_1/g_1.sum() - - -def original_wfb(pred, gting_55): - eing = np.abs(pred - gting_55) - dst, idst = distance_transform_edt(1 - gting_55, return_indices=True) - - king = fspecial_gauss(7, 5) - eting = eing.copy() - eting[gting_55 != 1] = eting[idst[:, gting_55 != 1] - [0], idst[:, gting_55 != 1][1]] - eaing = convolve(eting, king, mode='nearest') - maisfnasdf = eing.copy() - maisfnasdf[(gting_55 == 1) & (eaing < eing) - ] = eaing[(gting_55 == 1) & (eaing < eing)] - - bing = np.ones_like(gting_55) - bing[gting_55 != 1] = 2.0 - 1 * \ - np.exp(np.log(1 - 0.5) / 5 * dst[gting_55 != 1]) - ewing = maisfnasdf * bing - - tpwing = np.sum(gting_55) - np.sum(ewing[gting_55 == 1]) - fpwing = np.sum(ewing[gting_55 != 1]) - - ring = 1 - np.mean(ewing[gting_55 == 1]) - ping = tpwing / (tpwing + fpwing + np.finfo(np.float64).eps) - qing = 2 * ring * ping / (ring + ping + np.finfo(np.float64).eps) - - return qing - - -def fmeasure_calu(pred, gting_66, threshold_1): - threshold_1 = min(threshold_1, 1) - - label3 = np.zeros_like(gting_66) - label3[pred >= threshold_1] = 1 - - num_rec = np.sum(label3 == 1) - num_no_rec = np.sum(label3 == 0) - - label_and = (label3 == 1) & (gting_66 == 1) - num_and = np.sum(label_and == 1) - num_obj = np.sum(gting_66) - num_pred = np.sum(label3) - - fning = num_obj - num_and - fnmdp = num_rec - num_and - tning = num_no_rec - fning - - if num_and == 0: - pre_ftem = 0 - recall_ftem = 0 - f_metric = 0 - dice = 0 - speci_ftem = 0 - iou = 0 - - else: - iou = num_and / (fning + num_rec) - pre_ftem = num_and / num_rec - recall_ftem = num_and / num_obj - speci_ftem = tning / (tning + fnmdp) - dice = 2 * num_and / (num_obj + num_pred) - f_metric = ((2.0 * pre_ftem * recall_ftem) / (pre_ftem + recall_ftem)) - - return [pre_ftem, recall_ftem, speci_ftem, dice, f_metric, iou] - - -def alignment_term(pred, gtinga): - mu_pred = np.mean(pred) - mu_gt = np.mean(gtinga) - - align_pred = pred - mu_pred - align_gt = gtinga - mu_gt - - align_mat = 2 * (align_gt * align_pred) / (align_gt ** 2 + - align_pred ** 2 + np.finfo(np.float64).eps) - - return align_mat - - -def enhanced_alighment_term(align_mat): - enhanced = ((align_mat + 1) ** 2) / 4 - return enhanced - - -def enhanced_measure(pred, gtingb): - if np.sum(gtingb) == 0: - enhanced_mat = 1 - pred - elif np.sum(1 - gtingb) == 0: - enhanced_mat = pred.copy() - else: - align_mat = alignment_term(pred, gtingb) - enhanced_mat = enhanced_alighment_term(align_mat) - - score = np.sum(enhanced_mat) / (gtingb.size - 1 + np.finfo(np.float64).eps) - return score - - -def rgb_loader(path): - with open(path, "rb") as file_22: - img = Image.open(file_22) - return img.convert('RGB') - - -def binary_loader(path): - with open(path, "rb") as file_33: - img = Image.open(file_33) - return img.convert('L') - - -class TestDataset: - def __init__(self, image_root, gt_root, testsize): - self.testsize = testsize - self.images = [ - image_root + f for f in os.listdir(image_root) - if f.endswith('.jpg') or f.endswith('.png') - ] - self.gts = [ - gt_root + f for f in os.listdir(gt_root) if f.endswith('.tif') or f.endswith('.png')] - self.images = sorted(self.images) - self.gts = sorted(self.gts) - self.size = len(self.images) - self.index = 0 - self.mean = np.array( - [[[0.485]], [[0.456]], [[0.406]]], dtype=np.float32) - self.std = np.array( - [[[0.229]], [[0.224]], [[0.225]]], dtype=np.float32) - - def load_data(self): - image_1 = rgb_loader(self.images[self.index]) - image_1 = resize(image_1, (self.testsize, self.testsize)) # resize - image_1 = np.transpose(image_1, (2, 0, 1)).astype( - np.float32) # to tensor 1 - image_1 = image_1 / 255 # to tensor 2 - image_1 = (image_1 - self.mean) / self.std # normalize - - gting_222 = binary_loader(self.gts[self.index]) - name = self.images[self.index].split('/')[-1] - if name.endswith('.jpg'): - name = name.split('.jpg')[0] + '.png' - self.index += 1 - - return [image_1, gting_222, self.images[self.index-1], self.gts[self.index-1]] - - -if __name__ == '__main__': - - parser = ArgumentParser() - parser.add_argument('--pipeline_path', type=str, - default="pipeline/pranet_pipeline.json") - parser.add_argument('--data_path', type=str) - config = parser.parse_args() - - pipeline_path = config.pipeline_path - data_path = config.data_path - - IMAGESPTH = '{}/images/'.format(data_path) - GTSPATH = '{}/masks/'.format(data_path) - dataset = TestDataset(IMAGESPTH, GTSPATH, 352) - - INFER_RESULT = "infer_result/" - if not os.path.exists(INFER_RESULT): - os.mkdir(INFER_RESULT) - - streamManagerApi = StreamManagerApi() - ret = streamManagerApi.InitManager() - if ret != 0: - print("Failed to init Stream manager, ret=%s" % str(ret)) - sys.exit() - - with open(pipeline_path, "r") as file: - json_str = file.read() - - pipeline = json.loads(json_str) - pipelineStr = json.dumps(pipeline).encode() - - ret = streamManagerApi.CreateMultipleStreams(pipelineStr) - if ret != 0: - print("Failed to create Stream, ret=%s" % str(ret)) - sys.exit() - - Thresholds = np.linspace(1, 0, 256) - threshold_IoU = np.zeros((dataset.size, len(Thresholds))) - threshold_Dice = np.zeros((dataset.size, len(Thresholds))) - Smeasure = np.zeros(dataset.size) - wFmeasure = np.zeros(dataset.size) - MAE = np.zeros(dataset.size) - - for i in tqdm(range(dataset.size)): - image, gting, image_path, gt_path = dataset.load_data() - gting = np.asarray(gting, np.float32) - - print(image_path) - image = np.array(image).astype(np.float32) - infer(image_path, streamManagerApi) - - RESPATH = INFER_RESULT + str(i) + ".png" - while True: # 轮询, 等待异步线程 - time.sleep(0.1) - try: - pred_mask = np.array(Image.open(RESPATH)) - if not pred_mask.dtype == np.uint8: - continue - break - except (OSError, FileNotFoundError, PIL.UnidentifiedImageError, SyntaxError): - pass - gt_mask = np.array(Image.open(gt_path)) - - pred_mask = cv2.resize(pred_mask, dsize=gting.shape) - pred_mask = pred_mask.transpose(1, 0, 2) - - if len(pred_mask.shape) != 2: - pred_mask = pred_mask[:, :, 0] - if len(gt_mask.shape) != 2: - gt_mask = gt_mask[:, :, 0] - - assert pred_mask.shape == gt_mask.shape - - gt_mask = gt_mask.astype(np.float64) / 255 - gt_mask = (gt_mask > 0.5).astype(np.float64) - pred_mask = pred_mask.astype(np.float64) / 255 - - Smeasure[i] = structure_measure(pred_mask, gt_mask) - wFmeasure[i] = original_wfb(pred_mask, gt_mask) - MAE[i] = np.mean(np.abs(gt_mask - pred_mask)) - - threshold_E = np.zeros(len(Thresholds)) - threshold_F = np.zeros(len(Thresholds)) - threshold_Pr = np.zeros(len(Thresholds)) - threshold_Rec = np.zeros(len(Thresholds)) - threshold_Iou = np.zeros(len(Thresholds)) - threshold_Spe = np.zeros(len(Thresholds)) - threshold_Dic = np.zeros(len(Thresholds)) - - for j, threshold in enumerate(Thresholds): - threshold_Pr[j], threshold_Rec[j], threshold_Spe[j], \ - threshold_Dic[j], threshold_F[j], threshold_Iou[j] = \ - fmeasure_calu(pred_mask, gt_mask, threshold) - - Bi_pred = np.zeros_like(pred_mask) - Bi_pred[pred_mask >= threshold] = 1 - threshold_E[j] = enhanced_measure(Bi_pred, gt_mask) - - threshold_Dice[i, :] = threshold_Dic - threshold_IoU[i, :] = threshold_Iou - - results = [] - result = [] - - column_Dic = np.mean(threshold_Dice, axis=0) - meanDic = np.mean(column_Dic) - maxDic = np.max(column_Dic) - - column_IoU = np.mean(threshold_IoU, axis=0) - meanIoU = np.mean(column_IoU) - maxIoU = np.max(column_IoU) - - result.extend([meanDic, meanIoU]) - results.append(["res", *result]) - - headers = ['meanDic', 'meanIoU'] - print(tabulate(results, headers=['dataset', *headers], floatfmt=".3f")) - print("#"*20, "End Evaluation", "#"*20) - - streamManagerApi.DestroyAllStreams()