概要
完成训练集
一、数据集获取
数据集来自:
https://teodecampos.github.io/chars74k/
具体为EnglishHnd.tgz,含有手写的数字和字母图片。
前10为数字,后面的是字母
每个文件夹含有55个手写样本,为png图片,大小为1200*900
二、数据集处理
过大的文件不利于KNN算法,首先要按比例缩小文件像素,其次转换为二值文件保存为txt,方便KNN算法计算。
下面代码基于大文件夹里嵌套了子文件夹,子文件里存图片集
```python
from PIL import Image
import os
import numpy as np
# 遍历文件夹
#定义图片处理函数()
#input_folder_path 目标文件夹
#output_folder_path 输出文件夹
#x = 0 重命名处理完毕后的文件名称用
def file_chu(input_folder_path,output_folder_path,x = 0):
for folder_name in os.listdir(input_folder_path):
# 合并路径,为路径+文件夹名,用来遍历文件夹
folder_path = os.path.join(input_folder_path, folder_name)
y = 0 # x 与 y 组合命名用,例:0_1
for filename in os.listdir(folder_path): # listdir返回是文件夹和文件列表
file_path = os.path.join(folder_path, filename) # 拼接文件地址,遍历文件
# 打开图像
img = Image.open(file_path)
# 调整大小(target_width = 75,target_height = 100)
resized_img = img.resize((target_width, target_height), Image.LANCZOS)
# 二值化处理
binary_img = resized_img.convert("1") # "1"表示二值化
# 将二值化后的图像转为NumPy数组
binary_array = np.array(binary_img)
binary_array = ~binary_array
# 保存为txt文件
txt_file_path = os.path.join(output_folder_path, "{}_{}".format(x,y) + '.txt')
y += 1
np.savetxt(txt_file_path, binary_array, fmt="%d", delimiter='')
print("图像处理完成!")
x += 1
if __name__ == '__main__':
# 输入和输出文件夹路径
input_folder_path = "你的路径"
output_folder_path = "你的输出路径"
# 目标图像大小
target_width = 75
target_height = 100
file_chu(input_folder_path,output_folder_path)
```