批量图像分割评估脚本:使用Python和OpenCV

在计算机视觉任务中,图像分割是一项重要的任务,而对分割结果进行评估则是验证模型性能的关键一环。本文将介绍如何使用Python和OpenCV编写一个简单的批量图像分割评估脚本,以评估分割模型的性能。

1. 问题背景

假设我们有一组GT(Ground Truth)图像和相应的KMeans算法生成的分割图像。我们想要批量评估这些分割图像与GT图像之间的相似度,以便量化模型的性能。先装包

pip install numpy opencv-python tqdm hausdorff

2. 脚本概览

首先,定义了一组评估指标,包括Dice系数、IoU(Intersection over Union)、灵敏度、PPV(Positive Predictive Value)以及Hausdorff距离的95th percentile。

def dice_coef(predict: np.ndarray, label: np.ndarray, epsilon: float = 1e-5) -> float:predict, label = transform_image_data(predict, label)intersection = (predict * label).sum()return (2. * intersection + epsilon) / (predict.sum() + label.sum() + epsilon)def iou_score(predict: np.ndarray, label: np.ndarray, epsilon: float = 1e-5) -> float:predict, label = transform_image_data(predict, label)intersection = (predict & label).sum()union = (predict | label).sum()return (intersection + epsilon) / (union + epsilon)def sensitivity(predict: np.ndarray, label: np.ndarray, epsilon: float = 1e-5) -> float:predict, label = transform_image_data(predict, label)intersection = (predict * label).sum()return (intersection + epsilon) / (label.sum() + epsilon)def ppv(predict: np.ndarray, label: np.ndarray, epsilon: float = 1e-5) -> float:predict, label = transform_image_data(predict, label)intersection = (predict * label).sum()return (intersection + epsilon) / (predict.sum() + epsilon)def hd95(predict: np.ndarray, label: np.ndarray, distance="euclidean"):predict, label = transform_image_data(predict, label)predict = predict.flatten()[..., None]label = label.flatten()[..., None]distance = hausdorff.hausdorff_distance(predict, label, distance=distance)return distance * 0.95

然后,我们编写了一个函数,该函数接受包含GT和分割图像的文件夹路径,并返回每个图像的评估指标。

def batch_evaluation(data_folder, extension='.png'):gt_files = glob.glob(data_folder + '/gt*' + extension)mask_files = glob.glob(data_folder + '/mask*' + extension)dice_scores = []iou_scores = []sensitivity_scores = []ppv_scores = []hd95_distances = []for gt_file, mask_file in tqdm(zip(gt_files, mask_files), total=len(gt_files)):gt_image = cv2.imread(gt_file, 0)mask_image = cv2.imread(mask_file, 0)dice_scores.append(dice_coef(mask_image, gt_image))iou_scores.append(iou_score(mask_image, gt_image))sensitivity_scores.append(sensitivity(mask_image, gt_image))ppv_scores.append(ppv(mask_image, gt_image))hd95_distances.append(hd95(mask_image, gt_image))return {'dice_scores': dice_scores,'iou_scores': iou_scores,'sensitivity_scores': sensitivity_scores,'ppv_scores': ppv_scores,'hd95_distances': hd95_distances}

最后,我们使用这个函数对指定文件夹中的所有图像进行评估,并输出结果。

# 执行批量评估
evaluation_results = batch_evaluation(data_folder)# 输出结果
print("Dice Scores:", evaluation_results['dice_scores'])
print("IOU Scores:", evaluation_results['iou_scores'])
print("Sensitivity Scores:", evaluation_results['sensitivity_scores'])
print("PPV Scores:", evaluation_results['ppv_scores'])
print("HD95 Distances:", evaluation_results['hd95_distances'])

完整脚本如下


import glob
import cv2
import numpy as np
from tqdm import tqdmdef transform_image_data(predict: np.ndarray, label: np.ndarray):predict = predict.astype(np.bool_).astype(np.int_)label = label.astype(np.bool_).astype(np.int_)return predict, labeldef dice_coef(predict: np.ndarray, label: np.ndarray, epsilon: float = 1e-5) -> float:predict, label = transform_image_data(predict, label)intersection = (predict * label).sum()return (2. * intersection + epsilon) / (predict.sum() + label.sum() + epsilon)def iou_score(predict: np.ndarray, label: np.ndarray, epsilon: float = 1e-5) -> float:predict, label = transform_image_data(predict, label)intersection = (predict & label).sum()union = (predict | label).sum()return (intersection + epsilon) / (union + epsilon)def sensitivity(predict: np.ndarray, label: np.ndarray, epsilon: float = 1e-5) -> float:predict, label = transform_image_data(predict, label)intersection = (predict * label).sum()return (intersection + epsilon) / (label.sum() + epsilon)def ppv(predict: np.ndarray, label: np.ndarray, epsilon: float = 1e-5) -> float:predict, label = transform_image_data(predict, label)intersection = (predict * label).sum()return (intersection + epsilon) / (predict.sum() + epsilon)def hd95(predict: np.ndarray, label: np.ndarray, distance="euclidean"):predict, label = transform_image_data(predict, label)predict = predict.flatten()[..., None]label = label.flatten()[..., None]distance = hausdorff.hausdorff_distance(predict, label, distance=distance)return distance * 0.95def batch_evaluation(data_folder, extension='.png'):gt_files = glob.glob(data_folder + '/gt*' + extension)mask_files = glob.glob(data_folder + '/mask*' + extension)dice_scores = []iou_scores = []sensitivity_scores = []ppv_scores = []hd95_distances = []for gt_file, mask_file in tqdm(zip(gt_files, mask_files), total=len(gt_files)):gt_image = cv2.imread(gt_file, 0)mask_image = cv2.imread(mask_file, 0)dice_scores.append(dice_coef(mask_image, gt_image))iou_scores.append(iou_score(mask_image, gt_image))sensitivity_scores.append(sensitivity(mask_image, gt_image))ppv_scores.append(ppv(mask_image, gt_image))hd95_distances.append(hd95(mask_image, gt_image))return {'dice_scores': dice_scores,'iou_scores': iou_scores,'sensitivity_scores': sensitivity_scores,'ppv_scores': ppv_scores,'hd95_distances': hd95_distances}# 指定包含图像文件的文件夹路径
data_folder = '/path/to/your/data/folder'# 执行批量评估
evaluation_results = batch_evaluation(data_folder)# 输出结果
print("Dice Scores:", evaluation_results['dice_scores'])
print("IOU Scores:", evaluation_results['iou_scores'])
print("Sensitivity Scores:", evaluation_results['sensitivity_scores'])
print("PPV Scores:", evaluation_results['ppv_scores'])
print("HD95 Distances:", evaluation_results['hd95_distances'])

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/581442.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux:Vim

模式介绍: Vim具备6种基本模式和5中派生模式。 普通模式 启动后的默认模式,用于:移动光标、删除文本等待,常用命令: dd:删除当前行。[number]dd:连续执行number对应次数的dd命令&#xff0c…

判断电话号码是否重复-excel

有时候重复的数据不需要或者很烦人,就需要采取措施,希望以下的方法能帮到你。 1.判断是否重复 方法一: 1)针对第一个单元格输入等号,以及公式countif(查找记录数的范围,需要查找的单元格) 2…

Python Web --Django Web框架

场景 近日写了不少Python脚本,例如:爬虫、ocr、模型训练等。我认为可以更加了解python,因为近一个月使用Python给我的感觉比较好,代码比较简单,比java简单很多,而且python自己管理内存,更多依赖…

Linux: eBPF: bcc-tools:tcpdrop使用需要注意的问题

最近使用bcc-tools的时候注意到,bcc-tools(eBPF相关软件)的使用版本和内核的版本紧密程度非常高。因为要使用内核的函数或者结构体,所以就必须版本一致是必须的,不然会出现下面的警告或者错误: WARNING: tcp_drop() kernel function not found or traceable. The kernel …

Modbus RTU转Modbus TCP模块,RS232/485转以太网模块,YL102 多功能串口服务器模块

特点: ● Modbus RTU协议自动转换成Mobus TCP协议 ● 100M高速网卡,10/100M 自适应以太网接口 ● 支持 AUTO MDI/MDIX,可使用交叉网线或平行网线连接 ● RS232波特率从300到256000可设置 ● 工作方式可选择TCP Server, TCP Client, U…

四川天蝶电子商务有限公司助力商家赢在起跑线

随着电商行业的迅猛发展,越来越多的人选择在抖店上开设自己的店铺。作为一家专业的电子商务公司,四川天蝶电子商务有限公司为商家提供了一站式的抖店开店服务,帮助商家轻松开启电商之旅。 首先,四川天蝶电子商务有限公司拥有丰富的…

leetcode贪心算法题总结(一)

此系列分三章来记录leetcode的有关贪心算法题解,题目我都会给出具体实现代码,如果看不懂的可以后台私信我。 本章目录 1.柠檬水找零2.将数组和减半的最少操作次数3.最大数4.摆动序列5.最长递增子序列6.递增的三元子序列7.最长连续递增序列8.买卖股票的最…

事务管理解析:掌握Spring事务的必备技能!

AOP事务管理 1.1 Spring事务简介1.1.1 相关概念介绍1.1.2 转账案例-需求分析1.1.3 转账案例-环境搭建步骤1:准备数据库表步骤2:创建项目导入jar包步骤3:根据表创建模型类步骤4:创建Dao接口步骤5:创建Service接口和实现类步骤6:添加jdbc.properties文件步骤7:创建JdbcConfig配置…

八股文打卡day12——计算机网络(12)

面试题:HTTPS的工作原理?HTTPS是怎么建立连接的? 我的回答: 1.客户端向服务器发起请求,请求建立连接。 2.服务器收到请求之后,向客户端发送其SSL证书,这个证书包含服务器的公钥和一些其他信息…

机器学习之人工神经网络(Artificial Neural Networks,ANN)

人工神经网络(Artificial Neural Networks,ANN)是机器学习中的一种模型,灵感来源于人脑的神经网络结构。它由神经元(或称为节点)构成的层级结构组成,每个神经元接收输入并生成输出,这些输入和输出通过权重进行连接。 人工神经网络(ANN)是一种模仿生物神经系统构建的…

【操作系统】探究驱动奥秘:驱动程序设计的解密与实战

​🌈个人主页:Sarapines Programmer🔥 系列专栏:Linux专栏:《探秘Linux | 操作系统解密》⏰诗赋清音:月悬苍穹泛清辉,梦随星河徜徉辉。情牵天际云千层,志立乘风意自飞。 目录 &…

数据库——LAMP的搭建及MySQL基操

1.实验内容及原理 1. 在 Windows 系统中安装 VMWare 虚拟机,在 VMWare 中安装 Ubuntu 系统,并在 Ubuntu 中搭建 LAMP 实验环境。 2. 使用 MySQL 进行一些基本操作: (1)登录 MySQL,在 MySQL 中创建用户,并对…

【正则表达式】

概述 正则表达式又称规则表达式。(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。正则表达式并不仅限于某一种语…

spss统计软件:BM SPSS Statistics 27 (Win/mac)激活版

IBM SPSS Statistics 27 是一款专为数据分析、统计建模、预测分析和决策支持而设计的软件工具。作为SPSS Statistics系列的一部分,这个版本进一步增强了数据分析的功能,改善了用户体验,并确保了软件的稳定性与兼容性。 主要特点包括&#xff…

Spring Boot+RocketMQ 实现多实例分布式环境下的事件驱动

为什么要使用MQ? 在Spring Boot Event这篇文章中已经通过Guava或者SpringBoot自身的Listener实现了事件驱动,已经做到了对业务的解耦。为什么还要用到MQ来进行业务解耦呢? 首先无论是通过Guava还是Spring Boot自身提供的监听注解来实现的事…

Flink on K8S生产集群使用StreamPark管理

(一)直接部署(手动测试用,不推荐) Flink on Native Kubernetes 目前支持 Application 模式和 Session 模式,两者对比 Application 模式部署规避了 Session 模式的资源隔离问题、以及客户端资源消耗问题&am…

使用 async-profiler 分析 CPU 和 内存使用情况

async-profiler 是非常主流的 Java Profiling 工具之一,且对 Linux 支持良好,适合分析运行在服务器上的 Java 应用程序在 CPU 和内存上的占用情况。本文介绍一下 async-profiler 的安装和使用方法。 1. 安装 wget https://github.com/jvm-profiling-too…

人工智能 机器学习 深度学习:概念,关系,及区别说明

如果过去几年,您读过科技主题的文章,您可能会遇到一些新词汇,如人工智能(Artificial Intelligence)、机器学习(Machine Learning)和深度学习(Deep Learning)等。这三个词…

Tuxera NTFS for Mac2024免费Mac读写软件下载教程

在日常生活中,我们使用Mac时经常会遇到外部设备不能正常使用的情况,如:U盘、硬盘、软盘等等一系列存储设备,而这些设备的格式大多为NTFS,Mac系统对NTFS格式分区存在一定的兼容性问题,不能正常读写。 那么什…

WPF+Halcon 培训项目实战(1-5):Halcon安装,图像处理,Halcon简单模板匹配

文章目录 前言相关链接项目专栏我个人对就业市场的评价Halcon安装实战1-4:Halcon基础实战5:模板匹配[形状匹配]实战代码 结尾 前言 为了更好地去学习WPFHalcon,我决定去报个班学一下。原因无非是想换个工作。相关的教学视频来源于下方的Up主…