简体   繁体   中英

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, ie

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM