Python PPM格式的Ascii艺术
可能重复:Python PPM格式的Ascii艺术,python,python-3.x,ascii,ascii-art,Python,Python 3.x,Ascii,Ascii Art,可能重复: 这是更新的代码。我只需要它在同一行上打印字符,并在结尾处打断 import sys def main(filename): image = open(filename) #reads through the first three lines color = image.readline().splitlines() size_width, size_height = image.readline().split() max_color = image.rea
这是更新的代码。我只需要它在同一行上打印字符,并在结尾处打断
import sys
def main(filename):
image = open(filename)
#reads through the first three lines
color = image.readline().splitlines()
size_width, size_height = image.readline().split()
max_color = image.readline().splitlines()
#reads the body of the file
pixels = image.read().split()
red = 0
green = 0
blue = 0
r_g_b_value = []
#pulls out the values of each tuple and coverts it to its grayscale value
for i in pixels:
if i != "\n" or " ":
if len(i) == 3:
red = int(i[0]) * .3
green = int(i[1]) * .59
blue = int(i[2]) * .11
elif len(i) == 2:
red == int(i[0])
green == int(i[1])
blue == 0
elif len(i) == 1:
red == int(i[0])
green == 0
blue == 0
r_g_b_value = [red + green + blue]
grayscale = []
character = []
for j in r_g_b_value:
if int(j) <= .2:
character = "M"
elif int(j) > .2 and int(j) <= .4:
character = "#"
elif int(j) > .4 and int(j) <= .6:
character = "A"
elif int(j) > .6 and int(j) <= .8:
character = "@"
elif int(j) > .8 and int(j) <= 1:
character = "$"
elif int(j) > 1 and int(j) <= 1.2:
character = "0"
elif int(j) > 1.2 and int(j) <= 1.4:
character = "e"
elif int(j) > 1.4 and int(j) <= 1.6:
character = "a"
elif int(j) > 1.8 and int(j) <= 2:
character = "o"
elif int(j) > 2 and int(j) <= 2.2:
character = "="
elif int(j) > 2.25 and int(j) <= 2.5:
character = "+"
elif int(j) > 2.5 and int(j) <= 2.75:
character = ";"
elif int(j) > 2.75 and int(j) <= 3:
character = ":"
elif int(j) > 3 and int(j) <= 3.4:
character = ","
elif int(j) > 3.4 and int(j) <= 3.9:
character = "."
else:
character = " "
character += character
grayscale = [character]
print(grayscale)
导入系统
def main(文件名):
image=open(文件名)
#通读前三行
颜色=image.readline().splitlines()
大小\宽度,大小\高度=image.readline().split()
max_color=image.readline().splitlines()
#读取文件的正文
像素=image.read().split()
红色=0
绿色=0
蓝色=0
r_g_b_值=[]
#提取每个元组的值并将其转换为灰度值
对于i(以像素为单位):
如果我“\n”或“”:
如果len(i)==3:
红色=整数(i[0])*.3
绿色=整数(i[1])*.59
蓝色=整数(i[2])*.11
elif len(i)=2:
红色==int(i[0])
绿色==int(i[1])
蓝色==0
elif len(i)=1:
红色==int(i[0])
绿色==0
蓝色==0
r_g_b_值=[红色+绿色+蓝色]
灰度=[]
字符=[]
对于r_g_b_值中的j:
如果int(j).2和int(j).4和int(j).6和int(j).8和int(j)1和int(j)1.2和int(j)1.4和int(j)1.8和int(j)2和int(j)2.25和int(j)2.5和int(j)2.75和int(j)3和int(j)3.4和int(j)我猜错误来自:
for j in len(r_g_b_value):
(len返回一个int)
你可能想说
for j in r_g_b_value
是的,如果您想要一个范围,则需要使用
range()
或xrange()
@syrion,如果目标是迭代所有值,则是正确的,但在上下文中,使用range
…True没有意义。“我不应该在午夜如此开播。”赛里安对我来说是一种拖延(这让我觉得有点效率)我现在正在打印,但我想知道您是否有任何想法打印字符以保留图像?我得到了错误,但是否有人知道如何使用正确的尺寸打印出来您应该更新代码段我已经打印了,但每行只打印一个字符,我该如何把这些字符放在同一行上呢