將圖片轉(zhuǎn)化為字符串形式
使用方法
原理說明
代碼實(shí)現(xiàn)
使用例子
1. 使用方法
python main.py -i="image_path" -o="result_path" -s
-i 想要轉(zhuǎn)換圖片的路徑(可以是網(wǎng)絡(luò)路徑)
-o 轉(zhuǎn)換后的txt文件路徑(默認(rèn)為output.txt)
-s 打印轉(zhuǎn)換后的結(jié)果
2. 原理說明
(1)調(diào)整圖片的大小收苏,高度45屈尼, 寬度80(此比例在txt里接近1:1)
(2)將RGB圖片轉(zhuǎn)化為灰度圖
(3)將不同灰度的像素用不同的符號表示
3. 代碼實(shí)現(xiàn)
'''
通過灰度圖與字符集之間的映射來轉(zhuǎn)換圖片
'''
from PIL import Image
import urllib.request
from io import BytesIO
class ImageToChartSet(object):
def __init__(self, char_list = None) -> None:
super(ImageToChartSet, self).__init__()
self.char_list = char_list if char_list is not None else list("▁▂▃▅▆▇▇▇")[::-1]
self.num_char = len(self.char_list)
self.img_width = 80
self.img_height = 45
def rgbToChar(self, r, g, b, alpha=256):
if alpha == 0:
return ''
gray_value = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
resolution = 257.0 / self.num_char
return self.char_list[int(gray_value/resolution)]
def convert_image(self, img):
txt = ''
img = img.resize((self.img_width, self.img_height), Image.NEAREST)
for i in range(self.img_height):
for j in range(self.img_width):
txt += self.rgbToChar(*img.getpixel((j,i)))
txt += '\n'
return txt
def ImageOnline(url):
file = BytesIO(urllib.request.urlopen(url).read())
img = Image.open(file)
return img
def main(args):
import os
if args.image_path.startswith("http"):
img = ImageOnline(args.image_path)
elif args.image_path is None or not os.path.exists(args.image_path):
print("please check if you have set the true image path.")
return -1
else:
img = Image.open(args.image_path)
img2char = ImageToChartSet()
txt = img2char.convert_image(img)
if args.show:
print(txt)
with open(args.output_path, 'w') as f:
f.write(txt)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Image Convert to string")
parser.add_argument('-i','--image_path', default=None)
parser.add_argument('-o','--output_path', default="output.txt")
parser.add_argument('-s','--show', action="store_true", default=False)
args = parser.parse_args()
print(args)
main(args)
4. 使用例子
python main.py -i="https://gitee.com/jatq33/io/raw/master/2022/1.png" -o="test.txt" -s