【问题标题】:Skew a diagonal gradient to be vertical将对角渐变倾斜为垂直
【发布时间】:2016-09-29 17:49:27
【问题描述】:

作为图像,我在水平方向有一个不完全线性的渐变。以下是一些玩具数据:

g = np.ones((5,20))
for x in range(g.shape[0]):
    for y in range(g.shape[1]):
        g[x,y] += (x+y)*0.1+(y*0.01)

我想从根本上纠正渐变中的偏斜,使其水平,即渐变向右增加并且所有垂直切片都是恒定的。

这当然会生成一个 x 轴比输入图像更大的平行四边形。返回一个掩码的 Numpy 数组将是理想的。这是一个(可怕的)卡通来快速说明。

知道如何实现这一目标吗?谢谢!

【问题讨论】:

  • @dnalow 它很接近,但该解决方案没有插值。正如我在描述中所说,它不是一个线性渐变,所以需要做的不仅仅是一个倾斜。我猜每一行都需要插入到底行的值,然后才能在 x 中翻译。

标签: python arrays numpy transform


【解决方案1】:

您可以进行插值以确定偏度并再次进行插值以进行校正。

import numpy as np
from scipy.ndimage.interpolation import map_coordinates

m, n = g.shape
j_shift = np.interp(g[:,0], g[0,:], np.arange(n))
pad = int(np.max(j_shift))
i, j = np.indices((m, n + pad))
z = map_coordinates(g, [i, j - j_shift[:,None]], cval=np.nan)

这适用于示例图像,但您必须进行一些额外的检查才能使其在其他渐变上起作用。但它不适用于 x 方向上的非线性梯度。演示:

完整脚本:

import numpy as np
from scipy.ndimage.interpolation import map_coordinates

def fix(g):
    x = 1 if g[0,0] < g[0,-1] else -1
    y = 1 if g[0,0] < g[-1,0] else -1
    g = g[::y,::x]

    m, n = g.shape
    j_shift = np.interp(g[:,0], g[0,:], np.arange(n))
    pad = int(np.max(j_shift))
    i, j = np.indices((m, n + pad))
    z = map_coordinates(g, [i, j - j_shift[:,None]], cval=np.nan)

    return z[::y,::x]

import matplotlib.pyplot as plt

i, j = np.indices((50,100))
g = 0.01*i**2 + j

plt.figure(figsize=(6,5))
plt.subplot(211)
plt.imshow(g[::-1], interpolation='none')
plt.title('original')
plt.subplot(212)
plt.imshow(fix(g[::-1]), interpolation='none')
plt.title('fixed')
plt.tight_layout()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多