python-3.xnumpyopencvfor-loopnumpy-indexing

How to remove nested for loops and use numpy arrays insead


I have a video comprising of 580 frames. I need to be able to detect the green color from the video and create a mask so as to put zero values where green is found and the rest should be 255. I have converted the video in HSV format and am using nested for loops and it takes about an hour to do this I was wondering if there was a faster way of doing this.
Here is my current code

for i in range(0, len(temp)):
   temp[i] = cv2.cvtColor(temp[i], cv2.COLOR_BGR2HSV)
for k in range(0, len(temp)):
    for i in range(0, len(temp[k])):
        for j in range(0, len(temp[k][i])):
           if(temp[k][i][j][0] > 50 and temp[k][i][j][0] < 65 and temp[k][i][j][2] > 150):
               temp1[k][i][j][0] = 0
               temp1[k][i][j][1] = 0
               temp1[k][i][j][2] = 0
           else:
               temp1[k][i][j][0] = 255
               temp1[k][i][j][1] = 255
               temp1[k][i][j][2] = 255

temp is my HSV array and temp1 is the mask i am creating


Solution

  • Not a cv2 expert, but if it works like numpy arrays, then . . .

    for i in range(0, len(temp)):
       temp[i] = cv2.cvtColor(temp[i], cv2.COLOR_BGR2HSV)
       temp1[i] = (1 - cv2.inRange(temp[i], (50, 0, 150), (65, 255, 255)).astype(int)) * 255