如何删除嵌套的for循环并在insead中使用numpy数组

时间:2019-09-23 10:55:27

标签: python-3.x numpy opencv for-loop numpy-indexing

我有一个包含580帧的视频。我需要能够检测视频中的绿色并创建蒙版,以便在找到绿色的位置放置零值,其余的应为255。我已将视频转换为HSV格式,并使用嵌套的for循环,并且我花了大约一个小时才能做到这一点,我想知道这样做是否有更快的方法。
这是我当前的代码

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是我的HSV数组,而temp1是我正在创建的蒙版

1 个答案:

答案 0 :(得分:0)

不是cv2专家,但是如果它像numpy数组那样工作,则。 。 。

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