python - 为什么 2D 分配在 Numpy 中不能按预期工作?
问题描述
我有以下代码:
for (old_point, new_point) in zip(masked_indices, masked_new_indices):
row, col = old_point
new_row, new_col = new_point
new_img[row, col] = img[new_row, new_col]
其中new_img
和img
都是 1024x1024x3 ndarray,并且masked_indices
和masked_new_indices
都是 80000x2 ndarray。
为什么这个语句没有相同的行为?
new_img[masked_indices] = img[masked_new_indices]
有没有办法把这个for
循环优化成更 NumPy 风格的?
解决方案
我想到了。由于new_img
是三维的,我必须指定两个索引。尝试在单个索引中使用 2D 值是导致意外行为的原因。
这产生了我想要的效果,虽然它不是很漂亮:
new_img[masked_indices[:, 0], masked_indices[:, 1], :] = img[masked_new_indices[:, 0], masked_new_indices[:, 1], :]
推荐阅读
- iframe - 在 Office 应用程序嵌入式浏览器中显示 iframe
- python - 在自定义回调中访问丢失和模型
- .net - CloudBlobContainer 的 CreateIfNotExists() 总是抛出状态码 400
- apache-kafka - Debezium 应该只读取新的变化
- c++ -
>::tuple':没有重载函数需要 3 个参数。在 Qt 视觉工作室 2019 中 - python - 如何为 `object` 实现哈希函数
- elasticsearch - Elasticsearch 脚本数组大小
- c# - 如何跳过具有多个条件的“Where”子句中的条件?
- reactjs - useIonViewWillEnter 没有按预期工作-Ionic、ReactJS、Context API
- csv - 应用脚本 - 将 CSV 或 XLS 文件从云端硬盘上传到 Bigquery 或电子表格