iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python-图片之乐-ASCII 文本图形
  • 323
分享到

python-图片之乐-ASCII 文本图形

pythonascii 2023-08-30 10:08:34 323人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

ASCII:一个简单的字符编码方案 pillow模块:读取图像,访问底层数据 numpy模块:计算平均值 import sys, random, argparseimport numpy as npimport mathfrom PIL i

ASCII:一个简单的字符编码方案

pillow模块:读取图像,访问底层数据
numpy模块:计算平均值

import sys, random, argparseimport numpy as npimport mathfrom PIL import Image

定义灰度等级和网格

定义两种灰度等级作为全局值,用于将亮度值转换为ASCII 字符

从最黑暗变到最亮

# 70 levels of graygscale1 = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "# 10 levels of graygscale2 = '@%#*+=-:. '

http://paulbourke.net/dataformats/asciiart/

准备图像,并分割成网格

cols = 80scale = 0.43# open the image and convert to grayscaleimage = Image.open('youling.png').convert("L")# store the image dimensions  # image.sizeW, H = image.size[0], image.size[1]# compute the tile width  根据用户给定列数(cols)计算每个网格的宽度w = W/cols# compute the tile height based on the aspect ratio and scale of the fonth = w/scale# compute the number of rows to use in the final gridrows = int(H/h)

w网格的宽 = W图片的宽 / cols列数
h网格的高度 = w网格的宽 / 垂直比例系数scale
rows行 总共有多少行

Pillow模块里的convert()函数可以将图像从一种模式转换为另一种模式
convert(‘L’)将原始图像转换为灰度图像 L is luminance:是图像亮度的单位
convert(‘1’)将原始图像转换为黑白模式
convert(‘P’, palette=Image.ADAPTIVE, colors=1)将原始图像转换为使用颜色调色板的单色模式,colors=2,图片只有2种颜色
还有RGB、RGBA,CMYK,LAB,HSV,YCbCr、XYZ等等模式

CMYK代表青、洋红、黄和黑色,是一种用于印刷的颜色模式。它是印刷过程中使用的四种油墨颜色的缩写,包括青色(Cyan)、洋红色(Magenta)、黄色(Yellow)和黑色(Key),通过它们的不同组合可以得到各种颜色和色调。相对于RGB颜色模式(红、绿、蓝),CMYK颜色模式更适合印刷。

计算平均亮度

计算灰度图像中每一小块的平均亮度

def getAverageL(image):    # get the image as a numpy array    im = np.array(image)    # get the dimensions    w,h = im.shape    # get the average    return np.average(im.reshape(w*h))

将 image 转换成一个 numpy数组,此时 im 成为一个二维数组,包含每个像素的亮度

保存该图像的尺寸

numpy.average()计算该图像中的亮度平均值,做法是用 numpy.reshape()先将维度为宽和高(w,h)的二维数组转换成扁平的一维,其长度是宽度乘以高度(w*h)。然后 numpy.average()调用对这些数组值求和并计算平均值

从图像生成 ASCII 内容

在这里插入图片描述

# an ASCII image is a list of character stringsaimg = []# generate the list of tile dimensionsfor j in range(rows):    # 计算每个图像小块的起始和结束 y 坐标    y1 = int(j*h)    y2 = int((j+1)*h)    # correct the last tile    if j == rows-1:        y2 = H    # append an empty string    aimg.append("")    for i in range(cols):        # crop the image to fit the tile        x1 = int(i*w)        x2 = int((i+1)*w)        # correct the last tile        if i == cols-1:            x2 = W        # crop the image to extract the tile into another Image object        img = image.crop((x1, y1, x2, y2))        # get the average luminance # 获取网格的平均亮度值        avg = int(getAverageL(img))        # look up the ASCII character for grayscale value (avg)        if moreLevels:        # 将平均亮度值[0,255]对用到70级灰度[0,69]        gsval = gscale1[int((avg*69)/255)]    else:        # 将平均亮度值[0,255]对用到10级灰度[0,9]        gsval = gscale2[int((avg*9)/255)]        # append the ASCII character to the string        aimg[j] += gsval

int((avg69)/255)
if avg = 255,可得int((avg
69)/255)=69,在该字符串中最后一个索引是69
在这里插入图片描述

命令行选项

接下来,为程序定义一些命令行选项。这段代码使用内置的 argparse 类:

parser = argparse.ArgumentParser(description="descStr")# add expected argumentsparser.add_argument('--file', dest='imgFile', required=True)parser.add_argument('--scale', dest='scale', required=False)parser.add_argument('--out', dest='outFile', required=False)parser.add_argument('--cols', dest='cols', required=False)parser.add_argument('--morelevels', dest='moreLevels', action='store_true')

包含指定图像文件输入的选项(唯一必须的参数)
设置垂直比例因子
设置输出文件名
设置 ASCII 输出中的文本列数
添加–morelevels 选项,让用户选择更多层次的灰度梯度

将 ASCII 文本图形字符串写入文本文件

最后,将生成的 ASCII 字符串列表,写入一个文本文件:

# open a new text filef = open(outFile, 'w')# write each string in the list to the new filefor row in aimg:f.write(row + '\n')# clean upf.close()

完整代码

import sys, random, argparseimport numpy as npimport mathfrom PIL import Image# 70 levels of graygscale1 = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "# 10 levels of graygscale2 = '@%#*+=-:. 'def getAverageL(image):    # get the image as a numpy array    im = np.array(image)    # get the dimensions    w,h = im.shape    # get the average    return np.average(im.reshape(w*h))def covertImageToAscii(fileName, cols, scale, moreLevels):    """    Given Image and dimensions (rows, cols), returns an m*n list of Images    """    # declare globals    global gscale1, gscale2    # open image and convert to grayscale    image = Image.open(fileName).convert('L')    # store the image dimensions    W, H = image.size[0], image.size[1]    print("input image dims: %d x %d" % (W, H))    # compute tile width    w = W/cols    # compute tile height based on the aspect ratio and scale of the font    h = w/scale    # compute number of rows to use in the final grid    rows = int(H/h)        print("cols: %d, rows: %d" % (cols, rows))    print("tile dims: %d x %d" % (w, h))        # check if image size is too small    if cols > W or rows > H:        print("Image too small for specified cols!")        exit(0)            # an ASCII image is a list of character strings    aimg = []    # generate the list of tile dimensions    for j in range(rows):        # 计算每个图像小块的起始和结束 y 坐标        y1 = int(j*h)        y2 = int((j+1)*h)        # correct the last tile        if j == rows-1:            y2 = H        # append an empty string        aimg.append("")        for i in range(cols):            # crop the image to fit the tile            x1 = int(i*w)            x2 = int((i+1)*w)            # correct the last tile            if i == cols-1:                x2 = W            # crop the image to extract the tile into another Image object            img = image.crop((x1, y1, x2, y2))            # get the average luminance # 获取网格的平均亮度值            avg = int(getAverageL(img))            # look up the ASCII character for grayscale value (avg)            if moreLevels:                # 将平均亮度值[0,255]对用到70级灰度[0,69]                gsval = gscale1[int((avg*69)/255)]            else:                # 将平均亮度值[0,255]对用到10级灰度[0,9]                gsval = gscale2[int((avg*9)/255)]            # append the ASCII character to the string            aimg[j] += gsval    # return text image    return aimg# main() functiondef main():    # create parser    descStr = "This program converts an image into ASCII art."    parser = argparse.ArgumentParser(description=descStr)    # add expected arguments    parser.add_argument('--file', dest='imgFile', required=True)    parser.add_argument('--scale', dest='scale', required=False)    parser.add_argument('--out', dest='outFile', required=False)    parser.add_argument('--cols', dest='cols', required=False)    parser.add_argument('--morelevels', dest='moreLevels', action='store_true')        # parse arguments    args = parser.parse_args()        imgFile = args.imgFile    # set output file    outFile = 'out.txt'    if args.outFile:        outFile = args.outFile    # set scale default as 0.43, which suits a Courier font    scale = 0.43    if args.scale:        scale = float(args.scale)    # set cols    cols = 80    if args.cols:        cols = int(args.cols)    print('generating ASCII art...')    # convert image to ASCII text    aimg = covertImageToAscii(imgFile, cols, scale, args.moreLevels)         # open a new text file    f = open(outFile, 'w')    # write each string in the list to the new file    for row in aimg:        f.write(row + '\n')    # clean up    f.close()    print("ASCII art written to %s" % outFile)    # call mainif __name__ == '__main__':    main()

https://github.com/electronut/pp/blob/master/ascii/ascii.py

将完整代码保存到py文件中

打开终端,切换到ascii.py目录

输入下面代码

$ python ascii.py --file data/robot.jpg --cols 100

将 data/robot.jpg 替换为你想使用的图像文件的相对路径

在这里插入图片描述
使用vscode打开out.txt文件,使用Ctrl±可以缩小,可以看到全屏,只能看10灰度等级

还可使用notepad查看out.txt文件
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
–morelevels就是70灰度等级

在这里插入图片描述
在这里插入图片描述

来源地址:https://blog.csdn.net/weixin_64729620/article/details/132559047

--结束END--

本文标题: python-图片之乐-ASCII 文本图形

本文链接: http://www.lsjlt.com/news/382541.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python-图片之乐-ASCII 文本图形
    ASCII:一个简单的字符编码方案 pillow模块:读取图像,访问底层数据 numpy模块:计算平均值 import sys, random, argparseimport numpy as npimport mathfrom PIL i...
    99+
    2023-08-30
    python ascii
  • 图形图像处理之简单图片
    决定Android应用是否被用户接受的一个重要的原因就是用户界面,友好的用户界面就需要使用到图形图像处理技术,包括静态图片、动画和游戏都需要大量的图形图像处理,所谓游戏,其实就是提供更逼真,能模拟某种环境的用户界面,并根据某种规则响应用户的...
    99+
    2023-06-04
  • python之图形界面
    12.1 丰富的平台在编写python GUI程序前,需要决定使用哪个GUI平台。wxpython----跨平台pythonGUI工具包确保所选择的二进制版本要对应python的版本,例如,针对python2.3进行编译的wxpython并...
    99+
    2023-01-31
    图形界面 python
  • Python图片检索之以图搜图
    目录一、待搜索图二、测试集三、new_similarity_compare.py四、image_similarity_function.py五、结果一、待搜索图 二、测试集 三、...
    99+
    2024-04-02
  • python数字图像处理之基本图形的绘制
    目录引言1、画线条2、画圆3、多边形4、椭圆5、贝塞儿曲线6、画空心圆7、空心椭圆引言 图形包括线条、圆形、椭圆形、多边形等。 在skimage包中,绘制图形用的是draw模块,不要...
    99+
    2024-04-02
  • python3 文本变图片
    python3下的PIL叫做 pillowpython -m pip  install pillow创建目录 fonts,把微软雅黑字体放到下面。msyh.ttf#!/usr/bin/env python # -*- coding: utf...
    99+
    2023-01-31
    文本 图片
  • Python实现将图片转换为ASCII字符画
    目录前言字符画图片生成字符画文字的生成前言 要将图片转换为字符图其实很简单,我们首先将图片转换为灰度图像,这样图片的每个像素点的颜色值都是0到255,然后我们选用一些在文字矩形框内占...
    99+
    2024-04-02
  • opencv python简易文档之图片基本操作指南
    前言 最近在学习opencv,使用的是python接口。于是想着写些相关的笔记供以后参考,有不足之处希望大家指出。 使用python学习opencv需要下载opencv第三方库。 ...
    99+
    2024-04-02
  • Python图片处理之图片裁剪教程
    目录一、操作流程二、代码分析三、懒人一键复制代码一、操作流程 首先复制代码会吧? 1.有张照片 这是网上随便找的一张照片,自行保存测试 2.看看照片 运行代码,其中show_img...
    99+
    2024-04-02
  • JavaOpenCV图像处理之图形与文字绘制
    目录前言核心代码效果图前言 代码地址 序號名稱方法1圖像 添加文字Imgproc.putText2圖像 畫直綫Imgproc.line3圖像 畫橢圓Imgproc.ellipse4圖...
    99+
    2024-04-02
  • Python图片处理之图片采样处理详解
    目录一.图像采样处理原理二.图像采样实现三.图像局部采样处理四.总结一.图像采样处理原理 图像采样(Image Sampling)处理是将一幅连续图像在空间上分割成M×N...
    99+
    2024-04-02
  • Python 图片文字识别的实现之PaddleOCR
    目录项目使用项目结构环境部署1、安装Anaconda,构造虚拟环境2、依赖包下载测试代码参数补充总结前言 什么是OCR? 光学字符识别(Optical Character R...
    99+
    2024-04-02
  • Python图片处理之图片裁剪的示例分析
    小编给大家分享一下Python图片处理之图片裁剪的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!一、操作流程首先会吧?有张照片这是网上随便找的一张照片,自行保存测试看看照片运行代码,其中show_img函数是展示照...
    99+
    2023-06-15
  • python图片文本识别的简单实现
    http://blog.sina.com.cn/s/blog_628cc2b70101cjvp.html Python图片文本识别使用的工具是PIL和pytesser。因为他们使用到很多的python库文件,为了避免一个个工具的安装,建议...
    99+
    2023-01-31
    文本 简单 图片
  • python数字图像处理之基本形态学滤波
    目录引言1、膨胀(dilation)2、腐蚀(erosion)3、开运算(opening)4、闭运算(closing)5、白帽(white-tophat)6、黑帽(black-top...
    99+
    2024-04-02
  • python opencv常用图形绘制方法(线段、矩形、圆形、椭圆、文本)
    目录实现方法1)画线段 cv.line2)画圆形 cv.circle3)画矩形 cv.rectangle4)画椭圆形 cv.ellipse5)添加文本 cv.putText最近学了下...
    99+
    2024-04-02
  • 操作系统 GUI 的演变之旅:从文本到图形
    图形用户界面(GUI)已经成为现代计算机不可或缺的一部分。从早期的文本界面到当今先进的图形环境,操作系统GUI经历了一段漫长的演变之旅。本文将深入探讨这一旅程,从文本界面过渡到图形界面,以及沿途发生的重大变革。 文本界面:命令行的时代 ...
    99+
    2024-03-09
    操作系统GUI、图形用户界面、文本界面、命令行界面
  • python中opencv实现图片文本倾斜校正
    本项目为python项目需要安装python及python的opencv模块:opencv_python-4.0.1-cp37-cp37m-win32.whl 和 python的矩阵...
    99+
    2024-04-02
  • NodeJS实现图片文本分割
    本文实例为大家分享了NodeJS实现图片文本分割的具体代码,供大家参考,具体内容如下 var fs = require('fs'); var jpeg = require('j...
    99+
    2024-04-02
  • Python OpenCV实现基本图形绘制
    1.导入模块 import cv2 as cv import numpy as np 2.OpenCV绘图大致步骤 OpenCV 图形绘制步骤 (1)先定义基础画布canv...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作