如何使用 Python OpenCV 创建这种桶形/径向畸变?

JDS*_*JDS 2 python opencv image-processing computer-vision python-imaging-library

我正在使用 python / opencv 代码制作自定义虚拟现实耳机。我需要能够扭曲图像以创建“桶形扭曲”/“径向扭曲”效果。

一些图片来解释:

在此输入图像描述

在此输入图像描述

在此输入图像描述

我已经拥有source_image想要使用并向用户展示的内容,并且已经将它们并排放置。现在我只需要类似的东西out = cv2.createBarrelDistortion(source_image, params)。(我不介意能够调整一些参数,如畸变中心、畸变幅度等,这样我就可以让它看起来适合我得到的任何定制镜头。)

非常感谢任何帮助!

fmw*_*w42 9

以下是如何在 Python Wand 0.5.9 中执行此操作

http://docs.wand-py.org/en/0.5.9/index.html


输入:

在此输入图像描述

from wand.image import Image
import numpy as np
import cv2


with Image(filename='checks.png') as img:
    print(img.size)
    img.virtual_pixel = 'transparent'
    img.distort('barrel', (0.2, 0.0, 0.0, 1.0))
    img.save(filename='checks_barrel.png')
    # convert to opencv/numpy array format
    img_opencv = np.array(img)

# display result with opencv
cv2.imshow("BARREL", img_opencv)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)


结果:

在此输入图像描述

有关相同的示例和参数讨论,请参阅https://imagemagick.org/Usage/violets/#barrel 。

有关 Python/OpenCV 方法,请参阅https://hackaday.io/project/12384-autofan-automated-control-of-air-flow/log/41862- Correcting-for-lens- Distortions 。

  • `@lenik` OP 上面说 Python Wand 是可以接受的,他只需要得到可以在 OpenCV 中使用的凹凸数组形式的结果。所以我不知道你为什么降低我的答案。他说可以接受后我才发帖 (3认同)

San*_*are 6

我会使用 scipy ,但仅用于插值:

import numpy as np
from matplotlib import pyplot as plt

import scipy.ndimage
Run Code Online (Sandbox Code Playgroud)

....

#img: input image

# adjust k_1 and k_2 to achieve the required distortion
k_1 = 0.2
k_2 = 0.05

#img = imread("...")

h,w = [99,100] # img size

x,y = np.meshgrid(np.float32(np.arange(w)),np.float32(np.arange(h))) # meshgrid for interpolation mapping


# center and scale the grid for radius calculation (distance from center of image)
x_c = w/2 
y_c = h/2 
x = x - x_c
y = y - y_c
x = x/x_c
y = y/y_c

radius = np.sqrt(x**2 + y**2) # distance from the center of image

m_r = 1 + k_1*radius + k_2*radius**2 # radial distortion model

# apply the model 
x= x * m_r 
y = y * m_r

# reset all the shifting
x= x*x_c + x_c
y = y*y_c + y_c

distorted = scipy.ndimage.map_coordinates(img, [y.ravel(),x.ravel()])
distorted.resize(img.shape)
Run Code Online (Sandbox Code Playgroud)

....

我们使用一个简单的模型,当将点移得更远时,m_r乘以每个因子就会产生拉伸。x,y最后我们对扭曲点进行插值并得到我们的图像。

原始图像

图像扭曲