gpt4 book ai didi

python - 有没有一种好的方法可以在不检查边界符号的情况下对 Python numpy ndarrays 进行切片?

转载 作者:太空宇宙 更新时间:2023-11-03 17:08:55 25 4
gpt4 key购买 nike

这是我一直致力于快速对齐图像的一些代码的一部分。它运行良好,但语法很丑陋。有更好的写法吗?

def shift_int(image, base, y, x):
"""
Quickly shift an image with respect to a base and return a parameter that
is minimized when the images are well aligned, and not biased towards
large shifts

image -- The input image that is shifted
base -- The second image to match
y -- An offset along axis 0
x -- An offset along axis 1
"""
new_image = image.copy()
new_base = base.copy()

if y > 0:
new_image = new_image[:-y]
new_base = new_base[y:]

if y < 0:
new_image = new_image[-y:]
new_base = new_base[:y]

if x > 0:
new_image = new_image[:,:-x]
new_base = new_base[:,x:]

if x < 0:
new_image = new_image[:,-x:]
new_base = new_base[:,:x]

return np.mean((new_im-new_base)**2)

最佳答案

h, w = np.shape(new_image)
new_image = new_image[max(0, -y):min(h, h-y),max(0, -x):min(w, w-x)]

h, w = np.shape(new_base)
new_base = new_base[max(0, y):min(h, h+y),max(0, x):min(w, w+x)]

关于python - 有没有一种好的方法可以在不检查边界符号的情况下对 Python numpy ndarrays 进行切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com