Python索引器错误:列表分配索引超出范围

2024-09-28 21:18:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图打印一张图片在特定坐标(cx=125/cy=200)的RGB值,以及在这个坐标下的9个像素的RGB值,每个像素之间的距离为4。你知道吗

输出示例:

(from left to right: X-coordinate,    Y-coordinate,    R,   G,    B)

125, 200, 50, 200, 30
125, 196, 55, 250, 31
125, 192, 52, 271, 34
125, 188, 50, 284, 24
125, 184, 53, 234, 45
125, 180, 58, 243, 40
125, 176, 50, 225, 33
125, 172, 53, 263, 38
125, 168, 70, 237, 35
125, 164, 56, 201, 37

代码如下:

import cv2
import numpy as np

template = cv2.imread('C:\colorbars.png')
template = cv2.resize(template,(640,480))
height, width, depth = template.shape

tempx = []
tempy = []
b = [255]
g = [255]
r = [255]
i = 0
cx = 125
cy = 200

while i  < 10:
    x = cx * (float(width)) / 640
    tempx.insert(i, x)
    y = (cy-4) * (float(width)) / 480
    tempy.insert(i, y)
    b[i], g[i], r[i] = template[tempy[i]][tempx[i]]
    print tempx[i],tempy[i],r[i],g[i],b[i]
    i += 1

    cv2.imshow('template', template)

我选择R, G, B[255]是因为它们的最大值是255,对吗?你知道吗

我对Python还比较陌生,所以请原谅我缺乏知识。你知道吗

错误回溯:

C:\Users\Patrick:>C:\Python27\Lib\site-packages\test.py
125.0 261.333333333333 88 49 27
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\test.py", line 23, in <module>
b[i], g[i], r[i] = template[tempy[i]][tempx[i]]
IndexError: list assignment index out of range

Tags: importcoordinatelibtemplatergb像素floatwidth
1条回答
网友
1楼 · 发布于 2024-09-28 21:18:48

当您执行r= [255]时,它只创建一个元素的列表。你知道吗

当您使用i从0到10在r,g,b上迭代时,您试图访问一个不存在的索引存在。那个这就是为什么你得到index out of range error

如果要创建一个包含多个元素的列表,可以使用

r = ([initial_value] * 255) # creates a list of 255 element

相关问题 更多 >