python - 如何使用 python 将矢量场应用于二维图像?

标签 python matlab opencv matplotlib computer-vision

我使用 FyeldGenerator 库生成两个高斯随机场。如果绘制它们,它是这样的:

from FyeldGenerator import generate_field
import matplotlib.pyplot as plt
import numpy as np

# Helper that generates power-law power spectrum
def Pkgen(n):
    def Pk(k):
        return np.power(k, -n)
    return Pk

# Draw samples from a normal distribution
def distrib(shape):
    a = np.random.normal(loc=0, scale=1, size=shape)
    b = np.random.normal(loc=0, scale=1, size=shape)
    return a + 1j * b

shape = (512, 512)

field_x = generate_field(distrib, Pkgen(3), shape)
field_y = generate_field(distrib, Pkgen(3), shape)

plt.imshow(field_x, cmap='seismic')
plt.show()
plt.imshow(field_y, cmap='seismic')

enter image description here

然后我用 matplotlib 和 quiver 绘制矢量场。

enter image description here

现在我想在具有相同大小的随机场的图像上应用矢量场。我希望点 (i,j) 中的像素沿 quiver 函数中显示的方向(二维)移动。有什么办法吗?

这是在 matlab 上完成的此问题的示例,但在 3D 中:

Link of stackoverflow : Applying a vector field to image in matlab enter image description here

最佳答案

我认为您正在寻找的是 remap function in opencv . 如链接中所述,该函数根据索引数组 mapx 和 mapy 重新映射值: 𝚍𝚜𝚝(x,y)=𝚜𝚛𝚌(mapx(x,y),mapy(x,y))

如果我正确理解您想做什么,您首先需要为 mapx 和 mapy 创建基础索引:

mapx_base, mapy_base = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]))

然后使用矢量场对图像索引进行变形。这里我乘以增加变形。

mapx = mapx_base + field_x*30
mapy = mapy_base + field_y*30

最后对你的图像重新取样

img = cv2.imread('apple.jpg', 0).astype(np.float32)
deformed_apple = cv2.remap(img, mapx.astype(np.float32), mapy.astype(np.float32), cv2.INTER_LINEAR)

当然,如果您希望变形噪声较小,则需要对场进行平滑处理。

希望这对您有所帮助!

apple enter image description here

关于python - 如何使用 python 将矢量场应用于二维图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58697981/

相关文章:

python - 从 rtsp H.264 视频流中捕获单个图像

python - 如何定义没有 "TypeError: cannot determine truth value"的分段函数

python - 正则表达式结果为无

excel - Inf 在 Excel 中使用 Matlab xlswrite()

c++ - 在 C++ 中对两个用户定义的对象进行类型转换——可能吗?

python - Python OpenCV cv2.threshold无法在图像(jpg)中找到水平直线/行

python - atexit 处理程序不响应信号

python - python 3的密码学工具

matlab - Wolfram Alpha 和 MATLAB 以不同方式绘制传递函数

algorithm - 如何将坦克的左右电机速度转换为路径/曲率