简体   繁体   中英

How to speed up the loop over an OpenCV image in Python using Numpy?

The goal is to overcome the problem of slow execution of nested loops in python by using the built-in functions in numpy .

In the code below, I read an image with imread (colors: BGR) into src (a numpy array) and I define thresholds for each color (BGR respectively). Then I loop over src pixel-by-pixel (with two for nested loops), at each iteration I test if the current pixel meets the threshold (three conditions for each value: Blue, Green and Red), in the positive case (the pixel satisfies the conditions) I save its coordinates in a list (line number: i , column number: j ).

import cv2

src = cv2.imread('path_to_the_image')   # A numpy array with shape: (width, height, 3) ["3" for BGR]

cond = [10, 20, 30]  # A threshold for each color: Blue, Green and Red respectively

indexes = []  # To save pixel's coordinates which satisfies all three conditions

for i in range(0, src.shape[0]):  # Loop over lines (width)
    for j in range(0, src.shape[1]):  # Loop over columns (height)
        if src[i, j, 0] >= cond[0] and src[i, j, 1] >= cond[1] and src[i, j, 2] >= cond[2]:
            indexes.append((i, j))

So, I would like to know how to rewrite this code using numpy built-in functions to benefit from its speed?

You can do this:

a = np.array([[[1,2,3], [10,20,30]],
     [[40,50,60], [10, 30, 20]]
    ])

[*zip(*np.where((a > (10,20,30)).all(-1)))]

Output:

[(1, 0)]

Note : np.where((a > (10,20,30)).all(-1)) alone would give you [array([1]), array([0])] which might be better in some cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM