第3关:目标识别
import cv2
import os
import numpy as np
#如果有必要,可以增加其他函数来完成任务。可在此添加实现代码
# ********** Begin *********#
# ********** End **********#
def KNN_Classify(img, training_image_matrix, class_vector, k):
#使用KNN算法判断img的类型
# 请在此添加实现代码 #
# ********** Begin *********#
# 将图片转换为一维向量
img_vector = img.reshape(-1)
# 计算所有训练数据与测试数据之间的距离
distances = np.sqrt(np.sum((training_image_matrix - img_vector)**2, axis=1))
# 找到距离最近的k个点,并获取它们的标签
top_k_idx = np.argsort(distances)[:k]
top_k_labels = class_vector[top_k_idx]
# 统计k个点中出现次数最多的标签,并返回该标签作为预测结果
unique, counts = np.unique(top_k_labels, return_counts=True)
label_of_choice = unique[np.argmax(counts)]
return label_of_choice
# ********** End **********#
第4关:测试与分析
import cv2
import os
import numpy as np
#如果有必要,可以增加其他函数完成任务。可在此添加实现代码
# ********** Begin *********#
#上一关所写的分类器
def Distance(vector1, vector2):
diff = vector1-vector2
double_diff = diff**2
sum_of_double_diff = double_diff.sum()
dist = np.sqrt(sum_of_double_diff)
return dist
def KNN_Classify(img, training_image_matrix, class_vector, k):
N = len(training_image_matrix)
dist = np.zeros((N))
for i in range(N):
dist[i] = Distance(img, training_image_matrix[i])
sorted_indicies = dist.argsort()
match_count = {}
for i in range(k):
match_class = class_vector[sorted_indicies[i]]
match_count[match_class] = \
match_count.get(match_class,0)+1
match_count_in_order = sorted(match_count.items(), key=\
lambda item: item[1], reverse = True)
decided = match_count_in_order[0][0]
return decided
def Read(path):
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
rows, columns = img.shape
vec = img.reshape(rows*columns)
return vec
#读取并测试一个文件夹内的所有图片
def Test_Sub(dir,targetType,training_image_matrix, class_vector, k):
imgs = os.listdir(dir)
total = len(imgs)
match = 0
for s in imgs:
im = Read(dir + '/' + s)
t = KNN_Classify(im,training_image_matrix,class_vector,k)
if(t == targetType):
match += 1
return match,total
# ********** End **********#
def Test(dir,training_image_matrix, class_vector, k):
#测试dir所指的测试集目录下的所有图片,并统计测试结果
# 请在此添加实现代码 #
# ********** Begin *********#
bmpMatch,bmpTotal = Test_Sub(dir + '/' + 'BMP-2',0,training_image_matrix, class_vector, k)
print("BMP-2: %d/%d , %.1f%%" % (bmpMatch,bmpTotal,bmpMatch / bmpTotal * 100))
btrMatch,btrTotal = Test_Sub(dir + '/' + 'BTR-70',1,training_image_matrix, class_vector, k)
print("BTR-70: %d/%d , %.1f%%" % (btrMatch,btrTotal,btrMatch / btrTotal * 100))
tMatch,tTotal = Test_Sub(dir + '/' + 'T-72',2,training_image_matrix, class_vector, k)
print("T-72: %d/%d , %.1f%%" % (tMatch,tTotal,tMatch / tTotal * 100))
sumMatch = bmpMatch + btrMatch + tMatch
sumTotal = bmpTotal + btrTotal + tTotal
print("总: %d/%d , %.1f%%" % (sumMatch,sumTotal,sumMatch / sumTotal * 100))
# ********** End **********#
代码解释
import cv2模块,用于读取和处理图像
import cv2
import os模块,用于处理文件和目录
import os
import numpy模块,用于矩阵计算
import numpy as np
定义Distance函数,计算两个向量之间的欧式距离
def Distance(vector1, vector2):
# 计算差值
diff = vector1-vector2
# 计算平方差值
double_diff = diff**2
# 计算平方差值之和
sum_of_double_diff = double_diff.sum()
# 计算欧式距离
dist = np.sqrt(sum_of_double_diff)
return dist
定义KNN_Classify函数,使用KNN算法进行分类
def KNN_Classify(img, training_image_matrix, class_vector, k):
# 获取训练集中的样本数
N = len(training_image_matrix)
# 初始化距离数组
dist = np.zeros((N))
# 计算输入图像与每一个训练集中的图像的欧式距离
for i in range(N):
dist[i] = Distance(img, training_image_matrix[i])
# 对距离数组进行排序,并获取前k个最小值的索引
sorted_indicies = dist.argsort()
# 统计前k个最小值对应的类别,并按照出现次数从大到小排序
match_count = {}
for i in range(k):
match_class = class_vector[sorted_indicies[i]]
match_count[match_class] = match_count.get(match_class,0)+1
match_count_in_order = sorted(match_count.items(), key=lambda item: item[1], reverse=True)
# 返回出现次数最多的类别
decided = match_count_in_order[0][0]
return decided
定义Read函数,读取图像文件并将其转换成一维向量
def Read(path):
# 读取图像文件
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
# 获取图像行数和列数
rows, columns = img.shape
# 将二维图像转换成一维向量
vec = img.reshape(rows*columns)
return vec
定义Test_Sub函数,针对特定目标类型的测试集,统计分类结果并计算准确率
def Test_Sub(dir, targetType, training_image_matrix, class_vector, k):
# 获取测试集中所有图像文件列表
imgs = os.listdir(dir)
# 统计总共的测试样本数
total = len(imgs)
# 初始化匹配数为0
match = 0
# 遍历测试集中的每一个图像
for s in imgs:
# 读取图像文件并将其转换成一维向量
im = Read(dir + '/' + s)
# 对图像进行分类
t = KNN_Classify(im, training_image_matrix, class_vector, k)
# 判断分类结果是否正确,并累加匹配数
if(t == targetType):
match += 1
# 返回匹配数和总样本数
return match, total
定义Test函数,调用Test_Sub函数进行整体测试,并打印出各个类别的准确率以及总体准确率
def Test(dir, training_image_matrix, class_vector, k):
# 对每一个目标类型的测试集进行测试,统计分类结果并计算准确率
bmpMatch, bmpTotal = Test_Sub(dir + '/' + 'BMP-2', 0, training_image_matrix, class_vector, k)
print("BMP-2: %d/%d, %.1f%%" % (bmpMatch, bmpTotal, bmpMatch / bmpTotal * 100))
btrMatch, btrTotal = Test_Sub(dir + '/' + 'BTR-70', 1, training_image_matrix, class_vector, k)
print("BTR-70: %d/%d, %.1f%%" % (btrMatch, btrTotal, btrMatch / btrTotal * 100))
tMatch, tTotal = Test_Sub(dir + '/' + 'T-72', 2, training_image_matrix, class_vector, k)
print("T-72: %d/%d, %.1f%%" % (tMatch, tTotal, tMatch / tTotal * 100))
# 统计总体准确率
sumMatch = bmpMatch + btrMatch + tMatch
sumTotal = bmpTotal + btrTotal + tTotal
print("总: %d/%d, %.1f%%" % (sumMatch, sumTotal, sumMatch / sumTotal * 100))
生活不易,感谢关注与打赏哦