python 读取 object转换成数组 python将object转为字符_python


图像转字符画

原理:读取本地的图片字节流,通过字节流获取包含的每一个像素点的颜色值:rgb+a透明度通过一个颜色分析明暗对比,黑白最强烈的对比颜色,黑 - 灰gray色 - 白,rgb通过算法计算灰色,灰色的高低值决定我们填充字符的大小,填充完毕,字符画就完成

技术:

1.读取本地图片,获取字节流

2.怎么获取像素值及计算灰色

框架:

PILLOW

PIL 软件包提供了基本的图像处理功能,如:改变图像大小,旋转图像,图像格式转换,色场空间转换,图像增强,直方图处理,插值和滤波等等。

官网:https://pillow.readthedocs.io/en/latest/


python 读取 object转换成数组 python将object转为字符_jsonobject转list对象_02


掌握PIL框架的Image模块

效果图


python 读取 object转换成数组 python将object转为字符_jsonobject转list对象_03


python 读取 object转换成数组 python将object转为字符_Image_04


字体大小和字体样式会影响效果图

字体样式:华文、楷体

验证本地环境


python 读取 object转换成数组 python将object转为字符_python_05


导入模块

1.加载全部


import 框架名称:PIL
import PIL.Image


2.加载局部


from PIL import Image
from PIL import Image,ImageColor.....


导入本质就是别人封装好的py文件


python 读取 object转换成数组 python将object转为字符_jsonobject转list对象_06


代码实例

分析:gray 0黑色~255白色

接近0的颜色,就去使用体积大的字符

接近255的颜色,就去使用体积小的字符

字符列表的排列顺序:体积大~体积小排列

self.charList = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,"^`'.")

复制图片的路径


python 读取 object转换成数组 python将object转为字符_python_07


PIL知识点

1.打开


打开,旋转和显示图像(使用默认查看器)
以下脚本加载图像,将其旋转45度,然后使用外部查看器显示(通常在Unix上使用xv,在Windows上使用Paint程序)。

from PIL import Image
im = Image.open("bride.jpg")
im.rotate(45).show()


2.像素


Image.getpixel(xy)[资源]
返回给定位置的像素值。
参量
xy –坐标,以(x,y)给出。请参阅 坐标系。
退货
像素值。如果图像是多层图像,则此方法返回一个元组。


3.重置大小


Image.resize(size,resample = 3,box = None,reduce_gap = None)[资源]
返回此图像的调整大小的副本。

参量
size –请求的大小(以像素为单位),以2元组表示:(宽度,高度)。

重采样 –可选的重采样过滤器。这可以是一个PIL.Image.NEAREST,PIL.Image.BOX, PIL.Image.BILINEAR,PIL.Image.HAMMING, PIL.Image.BICUBIC或PIL.Image.LANCZOS。默认过滤器为PIL.Image.BICUBIC。如果图像的模式为“ 1”或“ P”,则始终设置为PIL.Image.NEAREST。请参阅:过滤器。

框 –可选的4元组浮点数,提供要缩放的源图像区域。值必须在(0,0,width,height)矩形内。如果省略或“无”,则使用整个源。

reduction_gap –通过分两步调整图像大小来应用优化。首先,使用将图像缩小为整数倍reduce()。其次,使用常规重采样来调整大小。最后一步更改大小不少于reducing_gap时间。 reducing_gap可以为None(不执行任何第一步)或应大于1.0。越大reducing_gap,结果越接近公平重采样。越小reducing_gap,调整大小的速度越快。随着reducing_gap大于或等于3.0,结果是公平的,从在大多数情况下重采样难以区分。默认值为无(无优化)。

退货
一个Image对象。

这会将给定图片的大小从调整为:(width, height)(width/2, height/2)

from PIL import Image

im = Image.open("hopper.jpg")

# Provide the target width and height of the image
(width, height) = (im.width // 2, im.height // 2)
im_resized = im.resize((width, height))


解包技术

*tuple 可以把元组系列解散,和长度相同的若干元素


tuple = (100,100,100)
正常:
tuple[0]
tuple[1]
tuple[2]
解包:
r,g,b = *tuple = 100,100,100


源代码

主要:文件路径需要根据自己的目录定义


self.imgPath 
file = open(file='/Users/lpf/Desktop/安康学院pyhton实训/python实训/第二天/output.txt',mode='w',encoding='utf-8')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 28 14:17:05 2020

@author: lpf

@content: 字符画像

"""

from PIL import Image

class App(): # 脚本应用
    
    def __init__(self): # 初始化属性
        self.imgPath = '/Users/lpf/Desktop/安康学院pyhton实训/python实训/第二天/dog.jpg'
        self.charList = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,"^`'.")
        self.charPic = ''
        

    def getImage(self): # 1 获取本地图片
        # open(1.距离 2.权限模式:r读取)
        img = Image.open(fp=self.imgPath,mode='r')
        
        # 测试:旋转图片角度
        # img.rotate(45).show()
        
        # size获取图片大小,元组类型(w,h)
        size = img.size
        print('size-',size)
        
        # resize重置大小
        self.img = img.resize((int(size[0]/2),int(size[1]/2)),Image.NEAREST)
        print('size-',self.img.size)
        
    
    def getPixel(self): # 2 获取本地图片的像素值
        
        for y in range(0, self.img.size[1]):
            
            for x in range(0, self.img.size[0]):
                
                # getpixel 获取像素值,返回rgb的元组或者a透明度
                self.charPic += self.getPixelGray(*self.img.getpixel((x,y)))
            
            # x轴结尾:跨行处理
            self.charPic += 'n'
    
    
    def getPixelGray(self,r,g,b,a=256): # 3 获取本地图片的像素值,计算灰色
        # 如果a=0,证明透明色,返回空格字符 
        if a == 0:
            return ' ' # 打断操作,返回
        else:
            # 计算灰色
            gray = int(0.2126*r+0.7152*g+0.0722*b)
            # 报错:gray 0~256 charList 0~70
            # 比例:颜色和字符的比例 256 / len(charList)
            # 下标:gray / 比例
            index = int(gray / (256 / len(self.charList)))
            char = self.charList[index]
            return char # 返回到调用的位置
        
        
    
    def save(self): # 4 存储本地
        
        # 创建一个本地文件
        file = open(file='/Users/lpf/Desktop/安康学院pyhton实训/python实训/第二天/output.txt',mode='w',encoding='utf-8')
        file.write(self.charPic) # 写入
        file.flush() # 清空缓存
        file.close() # 关闭文件
        print(file,'写入完毕')
        
    
    def run(self): # 5 统一执行函数:应用入口
        self.getImage()
        self.getPixel()
        self.save()


app = App()
app.run()


运行结果


runfile('/Users/lpf/Desktop/安康学院pyhton实训/python实训/第二天/4.练习-图像转字符画.py')
size- (640, 901)
size- (320, 450)
<_io.TextIOWrapper name='/Users/lpf/Desktop/安康学院pyhton实训/python实训/第二天/output.txt' mode='w' encoding='utf-8'> 写入完毕


python 读取 object转换成数组 python将object转为字符_元组_08