2

I am new to python, numpy and opencv. I am playing with the first example of harris corner detector from here. My objective is to get an ordered list of all the corners. With this simple code I am able to get the X and Y coordinates of the corners and their value:

height, width, depth = img.shape
print height, width
for i in range(0, height): #looping at python speed
  for j in range(0, (width)): 
    if dst[i,j] > 0.9*dst.max():
      print i, j, dst[i,j]

However, it is dead slow. I don't know how this is called but apparently with numpy one can loop through arrays at C speed and even assign values, example:

img[0:height, 0:width, 0:depth] = 0

Can I loop through an array and assign the position of interesting values in another variable? I.e. can I use this on my code to make it faster?

0

2 Answers 2

4

You can get a mask of elements that would pass the IF conditional statement. Next up, if you need the indices that would pass the condition, use np.where or np.argwhere on the mask. For the valid dst elements, index dst with the same mask, thus using boolean indexing. The implementation would look something like this -

mask = dst > 0.9*dst.max()
out = np.column_stack((np.argwhere(mask),dst[mask]))

If you would like to get those three printed outputs separately, you could do -

I,J = np.where(mask)
valid_dst = dst[mask]

Finally, if you would like to edit the 3D array img based on the 2D mask, you could do -

img[mask] = 0

This way, you would change the corresponding elements in img across all channels in one go.

Sign up to request clarification or add additional context in comments.

Comments

0

First of all if you are using Python 2.X you should use xrange instead of range, this speeds things up. range in Python 3.X has the same implementation as xrange in Python 2.X.

If you want to iterate over numpy arrays why not use the numpy enumerator for iteration?

# creating a sample img array with size 2x2 and RGB values
# so the shape is (2, 2, 3)
> img = np.random.randint(0, 255, (2,2,3))

> img
> array([[[228,  61, 154],
          [108,  25,  52]],

          [[237, 207, 127],
           [246, 223, 101]]])

# iterate over the values, getting key and value at the same time
# additionally, no nasty nested for loops
> for key, val in np.ndenumerate(img):
>     print key, val

# this prints the following
> (0, 0, 0) 228
> (0, 0, 1) 61
> (0, 0, 2) 154
> (0, 1, 0) 108
> (0, 1, 1) 25
> (0, 1, 2) 52
> (1, 0, 0) 237
> (1, 0, 1) 207
> (1, 0, 2) 127
> (1, 1, 0) 246
> (1, 1, 1) 223
> (1, 1, 2) 101

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.