转为字符数组_py字符打印照片

https://blog.csdn.net/xufive/article/details/103761569​blog.csdn.net 实验楼在线教育:这10个Python项目很有趣!​zhuanlan.zhihu.com
2dcc18d598587ad18fa2f86848cb2a40.png
# -*- coding: utf-8 -*-
from PIL import Image
import numpy as np


def print_photo(photo_file, width=120, k=2.0, reverse=False, outfile=None):
    """打印照片,默认120个字符宽度"""

    im = Image.open(photo_file).convert('L')  # 打开图片文件,转为灰度格式
    # 打印图像高度,k为矫正系数,用于矫正不同终端环境像素宽高比
    height = int(k * width * im.size[1] / im.size[0])
    arr = np.array(im.resize((width, height)))  # 转为NumPy数组
    if reverse:  # 反色处理
        arr = 255 - arr

    chs = np.array([' ', '.', '-', '+', '=', '*', '#', '@'])  # 灰度-字符映射表
    arr = chs[(arr / 32).astype(np.uint8)]  # 灰度转为对应字符

    if outfile:
        with open(outfile, 'w') as fp:
            for row in arr.tolist():
                fp.write(''.join(row))
                fp.write('n')
    else:
        for i in range(arr.shape[0]):  # 逐像素打印
            for j in range(arr.shape[1]):
                print(arr[i, j], end=' ')
            print()


if __name__ == '__main__':
    print_photo('C:/Users/F7687778/Desktop/tmp/fe.jpg', width=100, k=1.2, outfile='we.txt')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值