1

I have a python 3D list. Making it more clear, a list of list where each list is the four corner coordinate of a box. I have to filter all the boxes which are smaller than some given size.

Let us suppose this is the python list.

box = [[[4, 4], [4, 8], [8, 8], [8, 4]],
      [[8, 8], [8, 16], [16, 16], [16, 8]],
      [[20,16],[20,20],[24,20],[24,16]]
      ...
      ]

I have to filter all boxes with length and breadth less than or equal to 5.

filtered_box = [[[4, 4], [4, 8], [8, 8], [8, 4]],
                [[20,16],[20,20],[24,20],[24,16]]
               ...
               ]

This is my current code

filtered_box = []
for c in box:
    min_x, min_y = c[0]
    max_x, max_y = c[2]
    if max_x - min_x <= 5 & min_y - max_y <= 5:
        filtered_box.append(c)

This is working good but I need a more optimized solution. It can use numpy and convert back to python list or use the native python operations on list. I am using Python 3.

2
  • 2
    Have you attempted a numpy solution yet? If so, which part are you stuck on? This question is a little vague. Commented Jun 21, 2019 at 11:41
  • I iterated through the array in the same way. Can't find a vectorized solution. Commented Jun 21, 2019 at 11:42

2 Answers 2

1

Solution with numpy may look like this:

filtered_array = array[
    (np.abs(array[:, 0, 0] - array[:, 3, 0]) < 5) &
    (np.abs(array[:, 0, 1] - array[:, 3, 1]) < 5), :, :]

where array = np.array(box).

I guess this solution will be significantly faster than plain python if you have prepared data (numpy array). Transforming data from python list to numpy array will nullify any time gain.

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

Comments

0

This list comprehension replaces your for-loop construct:

import numpy as np

box = [
      [[4, 4], [4, 8], [8, 8], [8, 4]],
      [[8, 8], [8, 16], [16, 16], [16, 8]],
      [[20,16],[20,20],[24,20],[24,16]]
      ]

box = np.array(box) # convert to numpy array

# one-liner
filtered = [i for i in box if np.ptp(i[:,0]) <= 5 and np.ptp(i[:,1]) <= 5]

filtered = np.array(filtered) # if you want to convert to a numpy array

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.