python - Python和openCV数组IndexError:列表分配索引超出范围

标签 python arrays opencv opencv-python indexoutofrangeexception

有人知道我尝试将整数x放入暗数组时为什么会得到IndexError:列表分配索引超出范围吗?
我刚刚开始学习python&openCV(大约两个小时前(-;),并且我想要一个程序可以查看视频中的每一帧,在每一列中计算不在阈值(int x)中的像素,并将其放入数组变暗,但出现IndexError:列表分配索引超出范围。
我的python代码:

import cv2

vid = cv2.VideoCapture("136.mp4")

width = int(vid.get(3) / 2)
height = int(vid.get(4) / 2)

#frameCount = int(vid.get(1))

left = 300
right = 400
top = 210
bottom = 140

for i in range(0, 1599): #frame count
    vid.set(1, i)
    x, frameIn = vid.read()
    frameOut = cv2.resize(frameIn, (width, height))

    dark = [width - right - left]

    for y in range(left, width - right):
        x = 0
        for x in range(top, height - bottom):
            colR = frameOut[x, y, 2]
            colG = frameOut[x, y, 1]
            colB = frameOut[x, y, 0]

            if colR < 50 and colG > 60 and colB > 80:
                frameOut[x, y] = [255, 255, 255]
            else:
                x += 1


        dark[y - 1 - left] = x

    #cv2.imshow("video", frameOut)
    print(max(dark))
    cv2.waitKey(0)

最佳答案

您对如何创建数组有误。下一行:

dark = [width - right - left]
创建一个具有一个元素的Python list,该元素为width - right - left的值。但是,您可能想要做的是创建一个大小为width - right - left的零数组,可以通过执行以下操作创建:
import numpy as np

dark = np.zeros(width - right - left)
或者,如果您不想使用numpy:
dark = [0] * (width - right - left)

关于python - Python和openCV数组IndexError:列表分配索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64427856/

相关文章:

python - 查找 3d numpy 数组中特定行的索引

php - 这些在php中是什么?例如:$ _ COOKIE [],$ _ POST []等

python - 使用数组的前一个结果将许多二维数组乘以向量

python - 从客户端向服务器发送大量图像的有效方法

python - if python 中的 Elif 语句

python - 宽敞的管道?

python - 将类对象追加到列表中

python - 根据相关表中的另一个字段注释该表中的字段

python - 使用opencv python提取图片上的选定区域

c++ - 在第二个线程中显示图像,OpenCV?