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

基于NumPy优化图像线性变换:无循环实现方案咨询

NumPy图像线性变换:如何用向量化操作替代循环?

我正在学习NumPy,已经用for循环写了一个简单的图像线性变换代码,能实现预期效果,但想改成无循环的实现。尝试过meshgrid,但没法像循环那样通过i和j获取图像像素,虽然能应用变换,但像素赋值到新图像时总是出错,求解决思路。

原循环代码:

import numpy as np

M = np.array([
    [width, 0],
    [0, height]
])

T = np.array([
    [1, 3],
    [0, 1]
])

def transform_image(M, T):
    T_rel_M = abs(M @ T)
    new_img = np.zeros(T_rel_M.sum(axis=1).astype("int")).T
    
    for i in range(0, 440):
        for j in range(0, 440):
            x = np.array([j, i])
            coords = (T @ x)
            x = coords[0]
            y = coords[1]
            new_img[y, -x] = image[i, -j]
    
    return new_img

plt.imshow(transform_image(M, T))

编辑补充

感谢下方的解决方案,lezaf的方案和我之前的尝试非常相似,我之前缺失的关键步骤是将旧图像的像素正确赋值到新图像中。我对代码做了修改,移除了转置操作,并添加astype("int")以适配T矩阵中的浮点值:

def transform_image(M, T):
    T_rel_M = abs(M @ T)
    new_img = np.zeros(T_rel_M.sum(axis=1).astype("int")).T
    x_combs = np.array(np.meshgrid(np.arange(width), np.arange(height))).reshape(2,-1)
    coords = (T @ x_combs).astype("int")
    new_img[coords[1, :], -coords[0, :]] = image[x_combs[1, :], -x_combs[0, :]]
    
    return new_img

内容的提问来源于Stack Exchange,提问作者CMath

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:41:12