【问题标题】:How to fix this error “IndexError: image index out of range”?如何修复此错误“IndexError:图像索引超出范围”?
【发布时间】:2021-03-25 18:36:38
【问题描述】:

主要任务是显示.obj格式的图片

这是我的代码:

from PIL import Image
import re

scr_x = 800
scr_y = scr_x
half_scr_x = int(scr_x / 2)
half_scr_y = int(scr_y / 2)
img = Image.new('RGB', (scr_x+1, scr_y+1) , 'black')
canvas_pixels = img.load()
color = (255,255,255)
f = open('male_head.obj','r')
lines = f.read()
for line in lines.split('\n'):
    try:
        v, x, y, z, = re.split('\s+', line)
    except:
        continue
    if v == 'v':
        x = int((float(x) + 1) * half_scr_x)
        y = scr_y - int((float(y) + 1) * half_scr_y)
        canvas_pixels[x, y] = color
img.show()

错误:

canvas_pixels[x, y] = colour
IndexError: image index out of range

male_head.obj 文件位于项目文件夹中。

【问题讨论】:

标签: python image import python-imaging-library


【解决方案1】:

看起来颜色剂量不符合 canvas_pixels[x, y] 的规格。您应该查看颜色变量的结构。

【讨论】:

    【解决方案2】:

    您似乎希望文件中的 x 和 y 值在 (-1, 1) 范围内。如果你得到一个精确的 -1 或 1,你将得到一个超出范围的值。解决这个问题的最简单方法就是剪掉它:

    x = min(scr_x - 1, max(0, x))
    y = min(scr_y - 1, max(0, y))
    

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多