网上搜到的都不是很完美,所以自己借鉴了部分文章实现了一下,效果如下:
(ps:代码能用,但还是达不到理想状态,我已经把缺点写在里面了,追求完美的同志可以自己改改,改完记得在下面评论里面附上自己博客连接哦,便于后来的朋友找到你的代码)
最终效果
代码实现
from PIL import Image
import cv2
def img_RGBcolor_ascii(img, imt, r=3):
# img: input img img here is 3channel!
# r: raito params #由于不同控制台的字符长宽比不同,所以比例需要适当调整。
# window cmd:r=3/linux console r=
codeLib = '''@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. ''' # 生成字符画所需的字符集
count = len(codeLib)
gs = 10 # 10级灰度
# grays2 = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~i!lI;:,\"^.` "
# gs2 = 67 #67级灰度
# 宽(列)和高(行数)
w = img.shape[1]
h = img.shape[0]
ratio = r * float(w) / h # 调整长宽比-根据终端改变r
scale = w // 100 # 缩放尺度/取值步长,向下取整,每100/50个像素取一个 值越小图越小(scale 越大) 这个地方可能报错,调整一下大小整除。代码有待优化
image_file = imt.convert("L") # 转换为黑白图片,参数"L"表
for y in range(0, h, int(scale * ratio)): # 根据缩放长度 遍历高度 y对于h,x对应w
strline = ''
for x in range(0, w, scale): # 根据缩放长度 遍历宽度
gray = image_file.getpixel((x, y))
color_id = "\033[38;2;%d;%d;%dm%s" % (
img[y][x][0], img[y][x][1], img[y][x][2], codeLib[int(((count - 1) * gray) / 256)]) # 输出!
strline += color_id # 按行写入控制台
print(strline)
img = 'D:\\cm\\i.jpg'
fp = open(img, 'rb')
# 两种读取图片的方式有待优化成一个
image_file = Image.open(fp)
image_file = image_file.resize((int(image_file.size[0]), int(image_file