图片转换字符

在使用Python进行图片转换字符操作时遇到错误:TypeError: get_char() argument after * must be an iterable, not int。问题出在getpixel获取的是单个int类型的像素值,而非RGB格式。解决方案是在打开图片文件后,通过im = im.convert('RGB')将其转换为RGB格式,从而正确读取像素。" 73498732,6879977,Linux磁盘管理:分区、格式化与挂载,"['Linux', '磁盘管理', '文件系统']
摘要由CSDN通过智能技术生成
from PIL import Image
import argparse

# parameter analysis
parser = argparse.ArgumentParser()
parser.add_argument('file') #  Input file
parser.add_argument('-o', '--output') # Output file
# parser.add_argument('-shortname','--fullname')#存在简称和全程的格式在输入时可有可无
# parser.add_argument('--fullnage',type=?,default=?)#当然不使用简称也是可以的

parser.add_argument('--width', type = int, default = 80) # output alphabet width
parser.add_argument('--height', type = int, default = 80) # output alphabet height

# get parameters
args = parser.parse_args()

IMG = args.file
WIDH = args.width
HEIGHT =  args.height
OUTPUT = args.output

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

# Map 256 grayscale to 70 characters
def get_char(r,g, b, alpha = 256):
    if alpha == 0:
        return

    # Gets the character set length, which is 70
    length = len(ascii_char)

    # Convert the RGB value to a gray value with a range of 0-255
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

    # The grayscale range is 0-255, and the character set is only 70
    # You need to do the following to map the grayscale value to the specified character
    unit = (256.0 + 1 ) / length

    # Returns the character corresponding to the grayscale value
    #  # gray值对应到char_string中的位置(索引值)
    return ascii_char[int(gray / unit)]

if __name__ == '__main__':
    im = Image.open(IMG)
    im = im.resize((WIDH, HEIGHT), Image.NEAREST) # 注意这个函数第二个参数使用 Image.NEAREST,表示输出低质量的图片

    # 初始化字符串
    txt = ""
    # Iterate through each line in the picture
    for i in range(HEIGHT):
        # iterates through each column in the row
        for j in range(WIDH):
            # 将 (j,i) 坐标的 RGB 像素转为字符后添加到 txt 字符串
            txt += get_char(*im.getpixel((j, i)))
            #获取得到坐标 (i,j) 位置的 RGB 像素值(有的时候会包含 alpha 值),
            # 返回的结果是一个元组,例如 (1,2,3) 或者 (1,2,3,0)。
            # 我们使用 * 可以将元组作为参数传递给 get_char,同时元组中的每个元素都对应到 get_char 函数的每个参数。

        # 遍历完一行后需要增加换行符

        txt += '\n'
    # 输出到屏幕
    print(txt)

    # 字符画输出到文件
    if OUTPUT:
        with open(OUTPUT, 'w') as f:
            f.write(txt)
    else:
        with open("output.txt", 'w') as f:
            f.write()



运行问题
Traceback (most recent call last):
File “picturee.py”, line 54, in
txt += get_char(*im.getpixel((j, i)))
TypeError: get_char() argument after * must e an iterable, not int

解决办法:
需要将 im 转换为 RGB 格式,因为 getpixel 获取的是 RGB 的像素。
所以在 im = Image.open(IMG)之后加 im = im.convert(‘RGB’) 就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值