Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing a 2D numpy array inside a function using a function parameter

Say I have a 2D image in python stored in a numpy array and called npimage (1024 times 1024 pixels). I would like to define a function ShowImage, that take as a paramater a slice of the numpy array:

def ShowImage(npimage,SliceNumpy):
    imshow(npimage(SliceNumpy))

such that it can plot a given part of the image, lets say:

ShowImage(npimage,[200:800,300:500])

would plot the image for lines between 200 and 800 and columns between 300 and 500, i.e.

imshow(npimage[200:800,300:500])

Is it possible to do that in python? For the moment passing something like [200:800,300:500] as a parameter to a function result in error.

Thanks for any help or link. Greg

like image 778
gregory Avatar asked Dec 17 '25 11:12

gregory


1 Answers

It's not possible because [...] are a syntax error when not directly used as slice, but you could do:

  • Give only the relevant sliced image - not with a seperate argument ShowImage(npimage[200:800,300:500]) (no comma)

  • or give a tuple of slices as argument: ShowImage(npimage,(slice(200,800),slice(300:500))). Those can be used for slicing inside the function because they are just another way of defining this slice:

    npimage[(slice(200,800),slice(300, 500))] == npimage[200:800,300:500]
    

A possible solution for the second option could be:

import matplotlib.pyplot as plt
def ShowImage(npimage, SliceNumpy):
    plt.imshow(npimage[SliceNumpy])
    plt.show()

ShowImage(npimage, (slice(200,800),slice(300, 500)))
# plots the relevant slice of the array.
like image 159
MSeifert Avatar answered Dec 20 '25 00:12

MSeifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!