peng_python 发表于 2022-3-22 17:11:23

Python问题


小甲鱼极客python之效率革命绘图篇:
源代码如下:
from PIL import Image

img = Image.open('1.png')
out = img.convert("L")# 转换为灰度模式
#out.show()
print(out.size)
width,height = out.size
# 调节图片尺寸
# out = out.resize((int(width * 0.5), int(height * 0.5)))
# width, height = out.size

print(out.getpixel((10,10)))
print(out.size)
asciis = "$@#=+-."
texts = ''
for row in range(height):
    for col in range(width):
      gray = out.getpixel((col,row))
      texts += asciis
    texts += '\n'

with open('test1.txt','w') as file:
    file.write(texts)


想请问,为什么会报错:IndexError: string index out of range
图片大小设置为了512*512或者256**256都是一样的报错

suchocolate 发表于 2022-3-23 01:12:51

报错发全

peng_python 发表于 2022-3-23 16:03:17

suchocolate 发表于 2022-3-23 01:12
报错发全

Traceback (most recent call last):
File "C:/Users/admin/PycharmProjects/Xiao_jiayu/绘图篇/malilian.py", line 20, in <module>
(512, 512)
0
(256, 76)
    texts += asciis
IndexError: string index out of range

Process finished with exit code 1

suchocolate 发表于 2022-3-26 21:41:20

int(gray / 255 * 7) = 7
字符串 $@#=+-. 一共7个元素,index从0到6,没有7
页: [1]
查看完整版本: Python问题