Python and openCV array IndexError: list assignment index out of range

371 views Asked by At

Does anyone know why do i get IndexError: list assignment index out of range when i try to put integer x into the dark array?

I just started learning python & openCV (about two hours ago (-; ) and I want a programme that looks through every frame in the video, at each column counts pixels that are not in treshold (int x) and and puts it in an array dark. But I get IndexError: list assignment index out of range.

My python code:

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)
1

There are 1 answers

0
Tristan Nemoz On BEST ANSWER

You are mistaken on how to create an array. The following line:

dark = [width - right - left]

creates a Python list with one element, this one element being the value of width - right - left. What you likely wanted to do however was to create an array of zeros of size width - right - left, which you can create by doing this:

import numpy as np

dark = np.zeros(width - right - left)

or this, if you don't want to use numpy:

dark = [0] * (width - right - left)