python - Numpy as_strided() 分段错误
问题描述
我正在尝试“修补”步幅小于补丁大小的图像(即它们将重叠)。我这样做的方法是读取数组并使用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)
不知道这可能是什么原因。任何帮助都会很棒!
解决方案
推荐阅读
- python - 检查多个变量是否在相同限制之间的最简洁方法
- python - 图像中相同位置的像素值散点图
- sql - 可查询的
实体框架中的原始 SQL - javascript - TypeError:无法读取 null 的属性“类别”
- android - Google Play 控制台中的差异内部测试与许可证测试,用于 Google Assistant 与 Android 应用程序的集成
- python - 重新命名 Columns Pandas
- sql - 如何在sql中找到客户明智类别中的最大产品ID?
- mysql - MySQL ,哪个卖家在给定产品列表中的销售额最高
- visual-studio-code - 如何将 vscode 工具提示弹出样式更改为块样式?
- c# - 如何禁止在新窗口中禁用打开页面 - cefsharp