1 Star 1 Fork 1

吴烜/图像字符化

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
img2img.py 2.69 KB
一键复制 编辑 原始数据 按行查看 历史
吴烜 提交于 2024-11-25 01:03 +08:00 . #IB694K黑白照高宽修正
"""
@author: Viet Nguyen <nhviet1009@gmail.com>
"""
import argparse
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageOps
from utils import get_data
def get_args():
parser = argparse.ArgumentParser("Image to ASCII")
parser.add_argument("--input", type=str, default="data/input.jpg", help="Path to input image")
parser.add_argument("--output", type=str, default="data/output.jpg", help="Path to output text file")
parser.add_argument("--language", type=str, default="english")
parser.add_argument("--mode", type=str, default="standard")
parser.add_argument("--background", type=str, default="black", choices=["black", "white"],
help="background's color")
parser.add_argument("--num_cols", type=int, default=300, help="number of character for output's width")
args = parser.parse_args()
return args
def main(opt):
if opt.background == "white":
bg_code = 255
else:
bg_code = 0
char_list, font, 字符示例, scale = get_data(opt.language, opt.mode)
num_chars = len(char_list)
num_cols = opt.num_cols
image = cv2.imread(opt.input)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
height, width = image.shape
字符宽度, 字符高度 = font.getsize(字符示例)
字符高宽比 = 字符高度/字符宽度
cell_width = width / opt.num_cols
cell_height = 字符高宽比 * cell_width
num_rows = int(height / cell_height)
if num_cols > width or num_rows > height:
print("Too many columns or rows. Use default setting")
cell_width = 6
cell_height = 字符高宽比 * cell_width
num_cols = int(width / cell_width)
num_rows = int(height / cell_height)
out_width = 字符宽度 * num_cols
out_height = scale * 字符高度 * num_rows
out_image = Image.new("L", (out_width, out_height), bg_code)
draw = ImageDraw.Draw(out_image)
for i in range(num_rows):
line = "".join([char_list[min(int(np.mean(image[int(i * cell_height):min(int((i + 1) * cell_height), height),
int(j * cell_width):min(int((j + 1) * cell_width),
width)]) / 255 * num_chars), num_chars - 1)]
for j in
range(num_cols)]) + "\n"
draw.text((0, i * 字符高度), line, fill=255 - bg_code, font=font)
if opt.background == "white":
cropped_image = ImageOps.invert(out_image).getbbox()
else:
cropped_image = out_image.getbbox()
out_image = out_image.crop(cropped_image)
out_image.save(opt.output)
if __name__ == '__main__':
opt = get_args()
main(opt)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zhishi/ASCII-generator-rework.git
git@gitee.com:zhishi/ASCII-generator-rework.git
zhishi
ASCII-generator-rework
图像字符化
master

搜索帮助