2

I have a 2D numpy array. Lets consider the following example

    [[0,6,89,255,1,6,7]
    [0,255,89,255,1,1,7]
    [255,255,255,255,255,255,255]
    [1,2,3,4,5,6,7]
    [1,1,255,5,7,3,255]]

We need the coordinates of the box around a certain value. For example for value 255 the coordinates of the box around the value 255 will be upper left(0,0) and lower right (4,6).

How to do it efficiently in python.

Thanks a lot.

Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
Shan
  • 18,563
  • 39
  • 97
  • 132
  • 1
    Don't you mean upper left (0, 0)? Seems 255 is a confusing example since the box is the same size as the entire matrix. You mean that the box around 3 should be upper left (3, 2) and lower right (4, 5)? – Lauritz V. Thaulow Sep 08 '11 at 11:41
  • @lazyr Yes you are right... This is my mistake... I ll correct it the question... Thanks – Shan Sep 08 '11 at 12:12

1 Answers1

4

The answer is very similar to: Is there a "bounding box" function (slice with non-zero values) for a ndarray in NumPy?

from numpy import array, argwhere

A = array([[0  ,6  ,89 ,255,1  ,6  ,7  ],
           [0  ,255,89 ,255,1  ,1  ,7  ],
           [255,255,255,255,255,255,255],
           [1  ,2  ,3  ,4  ,5  ,6  ,7  ],
           [1  ,1  ,255,5  ,7  ,3  ,255]])

B = argwhere(A==255)
(ystart, xstart), (ystop, xstop) = B.min(0), B.max(0) 
Community
  • 1
  • 1