日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python实战1- 图片转字符画

發布時間:2025/3/19 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python实战1- 图片转字符画 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python實戰系列用于記錄實戰項目中的思路,代碼實現,出現的問題與解決方案
本文為第1篇–圖片轉字符畫
參考教程:https://www.cnblogs.com/MartinLwx/p/9143844.html

一、步驟

分析:字符畫原理是將圖片的灰度值與個人設定的字符集之間建立映射關系,不同區間的灰度值對應不同的字符,之后將圖片每一個像素對應的字符打印出來,即可獲得字符畫

  • 將原圖片轉化為灰度圖片
    方案一:利用灰度公式將像素的 RGB 值映射到灰度值
    gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
    方案二:利用PIL庫所帶的convert(“L”)函數轉化圖片

  • 將圖片的灰度值與個人設定的字符集之間建立映射關系
    可以自己設定,也可以找網上教程里給出的,下面將給出兩種參考方案
    方案一:

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

    方案二:

    ascii_char = list("qwertyuiop[]asdfghjkl;'zxcvbnm,./`~!@#$%^&<()*+{}:"?> |")

    經測試,方案二生成的圖片真實度更高

  • 將字符串保存到txt文件

  • 二、代碼實現

    注:IDE為Spyder,Python版本為3.6,推薦使用Anaconda,自帶Pillow庫。否則要提前安裝好pillow。
    pillow庫安裝教程:

  • 用管理員身份打開命令提示符
  • 輸入pip install pillow
  • 代碼實現如下:

    # -*- coding: utf-8 -*- """ Created on Fri Sep 28 23:23:44 2018@author: PastoralDog """ from PIL import Imageclass ASCIIart(object):def __init__(self,file):self.file=fileself.codelist = """qwertyuiop[]asdfghjkl;'zxcvbnm,./`~!@#$%^&<()*+{}:"?> |"""self.img=Image.open(file)self.count=len(self.codelist)def to_ASCII(self):img = self.img.convert("L")asciilist = ''for h in range(0,img.size[1]):for w in range(0,img.size[0]):gray = img.getpixel((w,h))pos = gray/256#asciilist = asciilist + self.codelist[int((self.count-1)*pos)]asciilist = asciilist + self.codelist[int((self.count-1)*pos)]+" "+self.codelist[int((self.count-1)*pos)]asciilist = asciilist+"\n"return asciilistdef to_txt(self):outfile = open('ASCIIart.txt', 'w')outfile.write(self.to_ASCII())outfile.close()def _resize(self,rate):width = self.img.size[0]height = self.img.size[1]scale = width / heightself.img = self.img.resize((int(width*rate), int(width*rate/scale) ))if __name__ == '__main__':file="test.jpg"img=ASCIIart(file)img.to_txt()

    三、出現的問題及解決方案

  • 圖像失真嚴重
    采用方案一的編碼生成的字符畫效果不是很好,改用方案二后得到解決

  • 圖像左右過于窄
    我們以下圖為例


    第二張核心代碼:

    asciilist = asciilist + self.codelist[int((self.count-1)*pos)]

    第三張核心代碼:

    asciilist = asciilist + self.codelist[int((self.count-1)*pos)]+" "+self.codelist[int((self.count-1)*pos)]

    由于第二張過窄,我們就加點東西(" "+self.codelist[int((self.count-1)*pos))使它豐滿起來

  • 本人水平有限,歡迎大家提出問題與建議。若代碼有看不懂的地方,也歡迎提出!

    總結

    以上是生活随笔為你收集整理的Python实战1- 图片转字符画的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。