我正在尝试“修补”步幅小于补丁大小的图像(即它们将重叠)。我这样做的方法是读取数组并使用as_strided(),然后将值复制到新数组。它适用于 uint8 格式的图像,但是,在 float32 上使用时会引发分段错误。MWE:
import numpy as np
def patch_sample(arr, patch_size=(128, 128), stride=64):
arr = np.ascontiguousarray(arr)
H, W, C = arr.shape
h, w = patch_size
patches_h = int((H - h) / stride + 1)
patches_w = int((W - w)/ stride + 1)
new_shape = (patches_h, patches_w, h, w, C)
new_strides = arr.itemsize * np.array(
[
W * arr.strides[1] * stride,
arr.strides[1] * stride,
W * arr.strides[1],
arr.strides[1],
1
]
)
patches_out = np.lib.stride_tricks.as_strided(
arr,
shape=new_shape,
strides=new_strides,
writeable=False
)
# Here segfault occurs
patches_out_cp = np.ascontiguousarray(patches_out)
# Segfault as well:
# patches_out_cp = patches_out.copy()
# Same for:
# patches_out_cp = np.empty_like(patches_out)
# np.copyto(patches_out_cp, patches_out)
patches_out_cp = patches_out_cp.reshape((-1, h, w, C))
return patches_out_cp
# No segfault
test_array = np.random.randint(0, 100, (1000, 1500, 3), dtype=np.uint8)
print(patch_sample(test_array).shape)
# Segfault
test_array = np.random.rand(1000, 1500, 3).astype(np.float32)
print(patch_sample(test_array).shape)
不知道这可能是什么原因。任何帮助都会很棒!