You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无循环将numpy数组值按指定索引(含浮点型)写入目标数组?

非规则图像像素映射的向量化实现与浮点索引反向插值

问题背景

我需要从原图像提取非矩形区域生成新图像,同时用映射数组记录新图像像素在原图像的位置。示例数据如下:

示例代码与数据

import numpy as np

# 初始化目标图像(5x5x3)
new_img = np.zeros((5,5,3))
# 初始输出(所有像素为0):
# array([[[0., 0., 0.],
#         [0., 0., 0.],
#         [0., 0., 0.],
#         [0., 0., 0.],
#         [0., 0., 0.]],
#        ...(其余行均为0)])

# 待映射的非规则图像(3x2x3)
poorly_shaped_img = np.array([
    [[0.56996145, 0.66969092, 0.39299133],
     [0.71405233, 0.81291533, 0.84920548]],
    [[0.75519416, 0.25214197, 0.45477072],
     [0.05180197, 0.64204567, 0.81518423]],
    [[0.91130947, 0.69654691, 0.99531231],
     [0.07430683, 0.18580811, 0.66368306]]
])

# 映射数组:记录poorly_shaped_img每个像素在new_img中的坐标
rounded_pixel_map = np.array([
    [[0,0],[0,2]],
    [[1,4],[2,4]],
    [[0,3],[4,2]]
])

# 期望输出的new_img
desired_output = np.array([
    [[0.56996145, 0.66969092, 0.39299133],
     [0., 0., 0.],
     [0.71405233, 0.81291533, 0.84920548],
     [0.91130947, 0.69654691, 0.99531231],
     [0., 0., 0.]],
    [[0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.],
     [0.75519416, 0.25214197, 0.45477072]],
    [[0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.],
     [0.05180197, 0.64204567, 0.81518423]],
    [[0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.]],
    [[0., 0., 0.],
     [0., 0., 0.],
     [0.07430683, 0.18580811, 0.66368306],
     [0., 0., 0.],
     [0., 0., 0.]]
])

当前实现与痛点

目前用嵌套循环实现像素赋值,但性能极差——我的非规则图像尺寸为4096×80,循环耗时严重:

for i in range(len(rounded_pixel_map)):
    for j in range(len(rounded_pixel_map[i])):
        pixel_coords = rounded_pixel_map[i][j]
        pixel_value = poorly_shaped_img[i][j]
        new_img[pixel_coords[0], pixel_coords[1]] = pixel_value

另外,实际生成非规则图像时使用了双线性插值,映射数组中的索引为浮点型,需要通过反向插值得到整数索引对应的正确像素值。

需求

  • 用向量化操作替代循环,实现高效的像素赋值
  • 处理浮点型映射索引的反向插值逻辑

内容的提问来源于stack exchange,提问作者Ross Davidson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 08:39:56