From dddf61b7a35cee55add3fe8a52ddfcc52c4ccf81 Mon Sep 17 00:00:00 2001 From: dong <2938690875@qq.com> Date: Wed, 16 Oct 2024 18:37:05 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 29 +++-------------------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/function.py b/function.py index 8de62e1..012044f 100644 --- a/function.py +++ b/function.py @@ -58,11 +58,7 @@ def classify(input_vector, dataSet, labels, k=3): """ 使用欧式距离的 kNN 分类算法。 """ - distances = [np.linalg.norm(input_vector - x) for x in dataSet] - k_indices = np.argsort(distances)[:k] - k_nearest_labels = [labels[i] for i in k_indices] - most_common = Counter(k_nearest_labels).most_common(1) - return most_common[0][0] + # 这里也写自己的代码实现 @@ -78,25 +74,7 @@ def load_dataset(directory): - np.array: 特征数据。 - np.array: 标签数据。 """ - features = [] - labels = [] - for filename in os.listdir(directory): - filepath = os.path.join(directory, filename) - - # 检查文件是否为图片类型(如 png 或 jpg) - if filename.endswith(".png") or filename.endswith(".jpg"): - # 从文件名提取标签 - label = int(filename.split('_')[0]) - - # 加载图片并转换为灰度图 - image = Image.open(filepath).convert('L') - - # 展平为一维向量并添加到特征列表中 - feature = np.array(image).flatten() - features.append(feature) - labels.append(label) - - return np.array(features), np.array(labels) + # 这里还写自己的代码实现 @@ -111,8 +89,7 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ - image = Image.open(filename).convert('L') - return np.array(image).flatten() + if __name__ == "__main__":