如何计算边缘图像或轮廓提取的准确率的python代码及其注释
时间: 2024-05-08 11:21:01 浏览: 16
在计算边缘图像或轮廓提取的准确率之前,我们需要先定义一些概念:
- True Positive (TP):正确识别为边缘的像素点数量。
- True Negative (TN):正确识别为非边缘的像素点数量。
- False Positive (FP):错误识别为边缘的像素点数量。
- False Negative (FN):错误识别为非边缘的像素点数量。
基于这些概念,我们可以计算以下指标:
- 准确率(Accuracy):分类正确的像素点数量占总像素点数量的比例,即 (TP + TN) / (TP + TN + FP + FN)。
- 精确率(Precision):正确识别为边缘的像素点数量占所有被识别为边缘的像素点数量的比例,即 TP / (TP + FP)。
- 召回率(Recall):正确识别为边缘的像素点数量占所有真实边缘的像素点数量的比例,即 TP / (TP + FN)。
- F1 Score:综合考虑精确率和召回率的指标,即 2 * Precision * Recall / (Precision + Recall)。
下面是计算边缘图像或轮廓提取的准确率的 Python 代码及其注释:
``` python
import cv2
import numpy as np
# 读取原图和边缘图像
img = cv2.imread('image.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(img_gray, 100, 200)
# 将边缘图像二值化
ret, edges = cv2.threshold(edges, 127, 255, cv2.THRESH_BINARY)
# 读取真实边缘图像
true_edges = cv2.imread('true_edges.jpg')
true_edges_gray = cv2.cvtColor(true_edges, cv2.COLOR_BGR2GRAY)
# 将真实边缘图像二值化
ret, true_edges_gray = cv2.threshold(true_edges_gray, 127, 255, cv2.THRESH_BINARY)
# 计算 TP、TN、FP、FN
TP = np.sum(np.logical_and(edges == 255, true_edges_gray == 255))
TN = np.sum(np.logical_and(edges == 0, true_edges_gray == 0))
FP = np.sum(np.logical_and(edges == 255, true_edges_gray == 0))
FN = np.sum(np.logical_and(edges == 0, true_edges_gray == 255))
# 计算准确率、精确率、召回率和 F1 Score
accuracy = (TP + TN) / (TP + TN + FP + FN)
precision = TP / (TP + FP)
recall = TP / (TP + FN)
f1_score = 2 * precision * recall / (precision + recall)
# 输出结果
print('Accuracy:', accuracy)
print('Precision:', precision)
print('Recall:', recall)
print('F1 Score:', f1_score)
```
在这段代码中,我们首先读取原图和边缘图像,并将边缘图像二值化。然后读取真实边缘图像,并将其二值化。接下来,我们计算 TP、TN、FP、FN。最后,我们计算准确率、精确率、召回率和 F1 Score,并输出结果。
需要注意的是,这段代码中使用了 NumPy 中的逻辑运算函数 np.logical_and() 来计算 TP、TN、FP、FN。这个函数可以对两个数组进行逐元素的逻辑运算,并返回一个逻辑数组。我们在这里使用它来计算两个二值化数组之间的交集。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)