美文网首页
python项目实战1:图片转字符

python项目实战1:图片转字符

作者: 晓话一下 | 来源:发表于2022-01-08 17:00 被阅读0次

    将图片转化为字符串形式

    1. 使用方法

    2. 原理说明

    3. 代码实现

    4. 使用例子

    1. 使用方法

    python main.py -i="image_path" -o="result_path" -s

    -i 想要转换图片的路径(可以是网络路径)

    -o 转换后的txt文件路径(默认为output.txt)

    -s 打印转换后的结果

    2. 原理说明

    (1)调整图片的大小,高度45, 宽度80(此比例在txt里接近1:1)

    (2)将RGB图片转化为灰度图

    (3)将不同灰度的像素用不同的符号表示

    3. 代码实现

    
    '''
    通过灰度图与字符集之间的映射来转换图片
    '''
    
    from PIL import Image
    import urllib.request
    from io import BytesIO
    
    
    class ImageToChartSet(object):
        def __init__(self, char_list = None) -> None:
            super(ImageToChartSet, self).__init__()
            self.char_list = char_list if char_list is not None else list("▁▂▃▅▆▇▇▇")[::-1]
            self.num_char = len(self.char_list)
            self.img_width = 80
            self.img_height = 45 
            
        def rgbToChar(self, r, g, b, alpha=256):
            if alpha == 0:
                return ''
            gray_value = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
            resolution = 257.0 / self.num_char
            return self.char_list[int(gray_value/resolution)]
        
        def convert_image(self, img):
            txt = ''
            img = img.resize((self.img_width, self.img_height), Image.NEAREST)
            for i in range(self.img_height):
                for j in range(self.img_width):
                    txt += self.rgbToChar(*img.getpixel((j,i)))
                txt += '\n'
            return txt
    
    def ImageOnline(url):
        file = BytesIO(urllib.request.urlopen(url).read())
        img = Image.open(file)
        return img
    
    
     
    def main(args):
        import os
        if args.image_path.startswith("http"):
            img = ImageOnline(args.image_path)
            
        elif args.image_path is None or not os.path.exists(args.image_path):
            print("please check if you have set the true image path.")
            return -1
        else:
            img = Image.open(args.image_path)
    
        img2char = ImageToChartSet()
        
        txt = img2char.convert_image(img)
        
        if args.show:
            print(txt)
        
        with open(args.output_path, 'w') as f:
            f.write(txt)
            
        
    if __name__ == "__main__":
        import argparse
        parser = argparse.ArgumentParser(description="Image Convert to string")
        parser.add_argument('-i','--image_path', default=None)
        parser.add_argument('-o','--output_path', default="output.txt")
        parser.add_argument('-s','--show', action="store_true", default=False)
        args = parser.parse_args()
        print(args)
        main(args)
    
    

    4. 使用例子

    python main.py -i="https://gitee.com/jatq33/io/raw/master/2022/1.png" -o="test.txt" -s

    原图片
    转化后字符串

    相关文章

      网友评论

          本文标题:python项目实战1:图片转字符

          本文链接:https://www.haomeiwen.com/subject/ncnecrtx.html