python图片转字符画

网上收集了几个用python生成字符画的小程序,除了cv那个,原理都差不多,都是利用灰度值公式。

 

附:安装依赖库的方法:

1.打开命令行窗口直接输入pip-V 回车,如果有输出,可以直接进入3

2.如果提示pip不是命令,也不是可运行程序,进入python安装目录的/Scripts目录下,在当前目录打开cmd,即可使用pip

3.执行pip install xxx即可安装需要的依赖库。如安装PIL:pip install PIL

安装cv库:pip install opencv-python

参考链接:https://www.runoob.com/w3cnote/python-pip-install-usage.html

 

1.图片转txt

# -*- coding=utf-8 -*-

import os.path

from PIL import Image

# # 命令行输入参数处理
# parser = argparse.ArgumentParser()
#
# parser.add_argument('file')  # 输入文件
# parser.add_argument('-o', '--output')  # 输出文件
#
# # 获取参数
# args = parser.parse_args()
#
# IMG = args.file
# OUTPUT = args.output
IMG = "c:/code/timg.jpg"

ascii_char = list("0123456789")


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


# 将256灰度映射到70个字符上
def get_char(r, g, b, alpha=256):
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    # 灰度值公式:0.2126 r + 0.7152 g + 0.0722 * b
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

    unit = (256.0 + 1) / length
    return ascii_char[int(gray / unit)]


if __name__ == '__main__':
    im = Image.open(IMG)
    txt = ""
    height = im.height
    width = im.width
    im = im.resize((width, height), Image.NEAREST)

    for i in range(height):
        for j in range(width):
            txt += get_char(*im.getpixel((j, i)))
        txt += '\n'

    # 字符画输出到文件
    newFile = os.path.splitext(IMG)[0] + ".txt"
    print("字符画图片:", newFile)
    with open(newFile, 'w') as f:
        f.write(txt)

2.图片转字符再转图片

# -*- coding:utf-8 -*-
import os

from PIL import Image, ImageFont, ImageDraw

# 命令行输入参数处理
# parser = argparse.ArgumentParser()
# parser.add_argument('file')
# parser.add_argument('-o','--output')
#
#
# #获取参数
# args = parser.parse_args()
# File = args.file
# OUTPUT = args.output

IMG = "c:/code/1.jpg"

ascii_char = list("01")


# 将像素转换为ascii码
def get_char(r, g, b, alpha=256):
    if alpha == 0:
        return ''
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    unit = (256.0 + 1) / length
    return ascii_char[int(gray / unit)]


if __name__ == '__main__':
    im = Image.open(IMG)
    WIDTH = int(im.width / 6)  # 高度比例为原图的1/6较好,由于字体宽度
    HEIGHT = int(im.height / 15)  # 高度比例为原图的1/15较好,由于字体高度
    im_txt = Image.new("RGB", (im.width, im.height), (255, 255, 255))
    im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
    txt = ""
    colors = []
    for i in range(HEIGHT):
        for j in range(WIDTH):
            pixel = im.getpixel((j, i))
            colors.append((pixel[0], pixel[1], pixel[2]))  # 记录像素颜色信息
            if (len(pixel) == 4):
                txt += get_char(pixel[0], pixel[1], pixel[2], pixel[3])
            else:
                txt += get_char(pixel[0], pixel[1], pixel[2])
        txt += '\n'
        colors.append((255, 255, 255))
    dr = ImageDraw.Draw(im_txt)
    font = ImageFont.load_default().font  # 获取字体
    x = y = 0
    # 获取字体的宽高
    font_w, font_h = font.getsize(txt[1])
    font_h *= 1.37  # 调整后更佳
    # ImageDraw为每个ascii码进行上色
    for i in range(len(txt)):
        if (txt[i] == '\n'):
            x += font_h
            y = -font_w
        dr.text([y, x], txt[i], colors[i])
        y += font_w
    # 输出
    newFile = os.path.splitext(IMG)[0] + "_charPicture.png"
    im_txt.save(newFile)

 

3.利用cv绘制字符画

# -*- coding:utf8 -*-
import os

import cv2

charSize = 2  # 字符尺寸
IMG = 'C:/code/1.jpg'

string = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
count = len(string)
img = cv2.imread(IMG)
u, v, _ = img.shape
c = img * 0 + 255
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

for i in range(0, u, 6):
    for j in range(0, v, 6):
        pix = gray[i, j]
        b, g, r = img[i, j]
        zifu = string[int(((count - 1) * pix) / 256)]
        cv2.putText(c, zifu, (j, i), cv2.FONT_HERSHEY_COMPLEX, charSize, (int(b), int(g), int(r)), 1)

newFile = os.path.splitext(IMG)[0] + "_charPicture.png"
cv2.imwrite(newFile, c)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值