Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the elements of a slice object in python

I'm using scipy.ndimage.label and scipy.ndimage.find_objects to find things in an image. It returns an array of slices. I am trying to get the coordinates of the object out of the slice but can't seem to find a way to get inside the slice object. Here is a simple example:

a = 1
b = 2
c = 13
d = 47
j = slice(a,b,None)
k = slice(c,d,None)
x = (j, k)

print(x)
print(x[0])
print(x[0].indices(2))
print(x[1].indices(2))

Output is:

(slice(1, 2, None), slice(13, 47, None))
slice(1, 2, None)
(1, 2, 1)
(2, 2, 1)

Basically I am looking for the ability to get the values for a, b, c, and d if I'm only given the slice tuple x. I thought indices would get me on the way but I'm not understanding it's behavior.

like image 572
DaveH Avatar asked Apr 06 '16 18:04

DaveH


1 Answers

Are you looking for the start, stop and step properties?

>>> s = slice(1, 2, 3)
>>> s.start
1
>>> s.stop
2
>>> s.step
3

slice.indices computes the start/stop/step for the indices that would be accessed for an iterable with the input length. So,

>>> s = slice(-1, None, None)
>>> s.indices(30)
(29, 30, 1)

Which means that you would take item 29 from the iterable. It is able to be conveniently combined with xrange (or range):

for item in range(*some_slice.indices(len(sequence))):
    print(sequence[item])

As a concrete example:

>>> a = range(30)
>>> for i in a[-2:]:
...   print(i)
... 
28
29
>>> s = slice(-2, None, None)
>>> for ix in range(*s.indices(len(a))):
...   print(a[ix])
... 
28
29
like image 186
mgilson Avatar answered Oct 07 '22 17:10

mgilson