Removing an element from a numpy array in Python

Viewed 42

I have a numpy array (detect_boxes) as shown below :

[[4.0458896e+02 0.0000000e+00 6.0321832e+02 2.5026520e+02 8.2438797e-01]
 [6.0857581e+02 0.0000000e+00 7.9714392e+02 2.4758081e+02 8.1139076e-01]
 [8.1018719e+02 4.9424463e+02 9.8861200e+02 7.3600000e+02 7.7758324e-01]
 [2.1146104e+02 0.0000000e+00 3.9479694e+02 2.5120786e+02 7.7443361e-01]
 [6.0805280e+02 4.9236230e+02 8.0093402e+02 7.3600000e+02 7.7402210e-01]
 [4.1667691e+02 4.9431726e+02 5.9711218e+02 7.3600000e+02 7.6940793e-01]
 [8.0647659e+00 0.0000000e+00 2.0194888e+02 2.4905939e+02 7.4543464e-01]
 [8.0722150e+02 0.0000000e+00 9.8927936e+02 2.4318008e+02 7.4441051e-01]
 [9.7559967e+00 4.9843073e+02 1.9808176e+02 7.3600000e+02 7.3720986e-01]
 [2.1477495e+02 4.9751501e+02 4.0028015e+02 7.3600000e+02 7.1077985e-01]
 [1.7097984e+01 1.0290663e+02 1.9678256e+02 2.3963664e+02 5.0910871e-02]]

Last item in the array of elements is confidence

conf = box[-1]

I need to remove the elements that confidence < 0.5. So this is how I did :

element_idx = 0
for box in detect_boxes:
         conf = box[-1]
         if conf<0.5:
             detect_boxes = np.delete(detect_boxes,element_idx)                
         element_idx += 1

This is not working., I get an error

   129     for box in boxes:
    130         # Pick confidence factor from last place in array
--> 131         conf = box[-1]
    132         if conf > 0.5:
    133             # Convert float to int and multiply corner position of each box by x and y ratio

IndexError: invalid index to scalar variable.

How could I delete elements with a threshold < 0.5

1 Answers

Use boolean indexing like:

out = detect_boxes[[False if e[-1] < 0.5 else True for e in detect_boxes]]

or just

out = detect_boxes[[e[-1] >= 0.5 for e in detect_boxes]]

or even better @MechanicPig suggestion:

out = detect_boxes[detect_boxes[:, -1] >= 0.5]

print(out):

array([[4.0458896e+02, 0.0000000e+00, 6.0321832e+02, 2.5026520e+02,
        8.2438797e-01],
       [6.0857581e+02, 0.0000000e+00, 7.9714392e+02, 2.4758081e+02,
        8.1139076e-01],
       [8.1018719e+02, 4.9424463e+02, 9.8861200e+02, 7.3600000e+02,
        7.7758324e-01],
       [2.1146104e+02, 0.0000000e+00, 3.9479694e+02, 2.5120786e+02,
        7.7443361e-01],
       [6.0805280e+02, 4.9236230e+02, 8.0093402e+02, 7.3600000e+02,
        7.7402210e-01],
       [4.1667691e+02, 4.9431726e+02, 5.9711218e+02, 7.3600000e+02,
        7.6940793e-01],
       [8.0647659e+00, 0.0000000e+00, 2.0194888e+02, 2.4905939e+02,
        7.4543464e-01],
       [8.0722150e+02, 0.0000000e+00, 9.8927936e+02, 2.4318008e+02,
        7.4441051e-01],
       [9.7559967e+00, 4.9843073e+02, 1.9808176e+02, 7.3600000e+02,
        7.3720986e-01],
       [2.1477495e+02, 4.9751501e+02, 4.0028015e+02, 7.3600000e+02,
        7.1077985e-01]])
Related