gpt4 book ai didi

python - 如何获得具有边界条件的图像面积?

转载 作者:行者123 更新时间:2023-11-30 23:26:27 26 4
gpt4 key购买 nike

scipy.ndimage 中的许多函数都接受可选的 mode=nearest|wrap|reflect|constant 参数,该参数确定如何处理函数需要来自的一些数据的情况图像区域之外(填充)。填充由NI_ExtendLine()内部处理。在 native 代码中。

我不想在填充数据上运行 ndimage 函数,而是想使用与 ndimage 相同的填充模式选择来获取填充数据。

这是一个示例(仅适用于 mode=nearest,假设为 2d 图像):

"""
Get padded data. Returns numpy array with shape (y1-y0, x1-x0, ...)
Any of x0, x1, y0, y1 may be outside of the image
"""
def get(img, y0, y1, x0, x1, mode="nearest"):
out_img = numpy.zeros((y1-y0, x1-x0))
for y in range(y0, y1):
for x in range(x0, x1):
yc = numpy.clip(y, 0, img.shape[0])
xc = numpy.clip(x, 0, img.shape[1])
out_img[y-y0, x-x0] = img[yc, xc]
return out_img

这样做是正确的,但速度,因为它一次迭代一个像素。

最好的(最快、最清晰、最Pythonic)的方法是什么?

最佳答案

def get(img, y0, y1, x0, x1, mode="nearest"):
xs, ys = numpy.mgrid[y0:y1, x0:x1]
height, width = img.shape

if mode == "nearest":
xs = numpy.clip(xs, 0, height-1)
ys = numpy.clip(ys, 0, width-1)

elif mode == "wrap":
xs = xs % height
ys = ys % width

elif mode == "reflect":
maxh = height-1
maxw = width-1

# An unobvious way of performing reflecting modulo
# You should comment this
xs = numpy.absolute((xs + maxh) % (2 * maxh) - maxh)
ys = numpy.absolute((ys + maxw) % (2 * maxw) - maxw)

elif mode == "constant":
output = numpy.empty((y1-y0, x1-x0))
output.fill(0) # WHAT THE CONSTANT IS

# LOADS of bounds checks and restrictions
# You should comment this
target_section = output[max(0, -y0):min(y1-y0, -y0+height), max(0, -x0):min(x1-x0, -x0+width)]
new_fill = img[max(0, y0):min(height, y1), max(0, x0):min(width, x1)]

# Crop both the sections, so that they're both the size of the smallest
# Use more lines; I'm too lazy right now
target_section[:new_fill.shape[0], :new_fill.shape[1]] = new_fill[:target_section.shape[0], :target_section.shape[1]]

return output

else:
raise NotImplementedError("Unknown mode")

return img[xs, ys]

关于python - 如何获得具有边界条件的图像面积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22520067/

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