数字识别之图像转为二进制数据

发布时间:2019-10-11 09:02:34编辑:auto阅读(2465)

    数字识别是人工智能的一个应用

    现在来实现如何将一个图片数字转为二进制的数据,并保存到为本中

    1. 图片是32x32的一个白底黑字的png图片
    2. 使用PIL模块获取像素,进行比对
    3. 存储数字二进制文件,方便后续训练数据使用

    代码在github托管

    部分代码展示

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    '''
    图片处理成32x32的二进制数据
    '''
    from PIL import Image
    
    # 打开要处理的图像
    img_src = Image.open('a.png')
    size = img_src.size
    # 转换图片的模式为RGBA
    img_src = img_src.convert('RGB')
    
    with open('1.txt','wb') as f:
        for i in range(size[0]):
            for j in range(size[1]):
                tmp = img_src.getpixel((j,i))
                if(tmp != (255,255,255)):
                    f.write(b'1')
                else:
                    f.write(b'0')
    

关键字