mardi 2 juillet 2019

Looping program causes index # is out of bounds for axis #

I'm pretty new to python and Opencv, but I have a few pieces from cv2 and random in mind for a simple test program to make sure I understood how these libraries worked.

I'm trying to create a program that effectively generates colored "snow", similar to what an old fashioned television shows when it has no signal.

Basically I generate a random color with random.randint(-1,256) to get a value between 0 and 255. I do it three times and store each in a different variable, randB/G/R. Then I do it twice more for coordinates randX/Y, using img.shape to get variables for width and height for the max number.

I don't think my variables are being interpreted as strings. If I quickly break the loop and print my variables, no errors are shown. If I remove the randX and randY variables and specify fixed coordinates or a range of [X1:Y1, X2:Y2] it doesn't crash.

import cv2
import numpy as np
import random

img = cv2.imread('jake_twitch.png', cv2.IMREAD_COLOR)
height, width, channels = img.shape

while True:
    randB = (random.randint(-1,256))
    randG = (random.randint(-1,256))
    randR = (random.randint(0,256))
    randX = (random.randint(0,width))
    randY = (random.randint(0,height))

    img[randX,randY] = [randB,randG,randR]
    cv2.imshow('Snow', img)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.imwrite('Snow.png', img)
cv2.destroyAllWindows

I would expect my code to run indefinitely coloring pixels random colors within a specified "box" defined by the width and height variables from img.shape.

it seems to start doing that, but If the program runs for more than about a second it crashes and spits out "IndexError: index 702 is out of bounds for axis 1 with size 702"




Aucun commentaire:

Enregistrer un commentaire