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:
假设我有一个存储在numpy数组中的python中的2D图像,称为npimage(1024倍1024像素)。我想定义一个函数ShowImage,它将一个numpy数组的参数作为参数:
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.
将绘制图像为200到800之间的行和300到500之间的行,即
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.
有可能在python中这样做吗?暂时将[200:800,300:500]之类的内容作为参数传递给函数导致错误。
Thanks for any help or link. Greg
感谢您的帮助或链接。格雷格
1 个解决方案
#1
2
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)仅给出相关的切片图像 - 不是单独的参数ShowImage(npimage [200:800,300:500])(无逗号)
-
or give a
tuple
ofslices
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:或者给出一个切片元组作为参数:ShowImage(npimage,(slice(200,800),slice(300:500)))。这些可以用于在函数内部进行切片,因为它们只是定义此切片的另一种方式:
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.
#1
2
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)仅给出相关的切片图像 - 不是单独的参数ShowImage(npimage [200:800,300:500])(无逗号)
-
or give a
tuple
ofslices
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:或者给出一个切片元组作为参数:ShowImage(npimage,(slice(200,800),slice(300:500)))。这些可以用于在函数内部进行切片,因为它们只是定义此切片的另一种方式:
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.