Python IndexError: list assignement index out of range

Python IndexError: list assignement index out of range

我正在尝试在特定坐标处打印图片的 RGB 值 (cx=125/cy=200) 以及该坐标下方另外 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

当您执行 r= [255] 时,它会创建一个仅包含一个元素的列表。

当您使用 i 从 0 到 10 遍历 r ,g,b 时,您试图访问的索引不是 exist.That 导致您得到 index out of range error[= 的原因13=]

如果您想创建一个具有多个初始值的列表,您可以使用

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