gpt4 book ai didi

python - 使用Python OpenCV捏缩/凸出变形

转载 作者:行者123 更新时间:2023-12-02 16:13:45 24 4
gpt4 key购买 nike

我想使用Python OpenCV在图像上应用收缩/凸起过滤器。结果应为以下示例:
https://pixijs.io/pixi-filters/tools/screenshots/dist/bulge-pinch.gif
我已经阅读了以下应该是过滤器正确公式的stackoverflow文章:Formulas for Barrel/Pincushion distortion
但是我正在努力在Python OpenCV中实现这一点。
我已经读过关于将滤镜应用于图像的 map :Distortion effect using OpenCv-python
据我了解,代码可能看起来像这样:

import numpy as np
import cv2 as cv

f_img = 'example.jpg'
im_cv = cv.imread(f_img)

# grab the dimensions of the image
(h, w, _) = im_cv.shape

# set up the x and y maps as float32
flex_x = np.zeros((h, w), np.float32)
flex_y = np.zeros((h, w), np.float32)

# create map with the barrel pincushion distortion formula
for y in range(h):
for x in range(w):
flex_x[y, x] = APPLY FORMULA TO X
flex_y[y, x] = APPLY FORMULA TO Y

# do the remap this is where the magic happens
dst = cv.remap(im_cv, flex_x, flex_y, cv.INTER_LINEAR)

cv.imshow('src', im_cv)
cv.imshow('dst', dst)

cv.waitKey(0)
cv.destroyAllWindows()
这是实现示例图像中呈现的失真的正确方法吗?非常感谢有关有用资源或示例的任何帮助。

最佳答案

在使自己熟悉了ImageMagick的源代码之后,我找到了一种将公式应用于失真的方法。借助OpenCV remap函数,这是使图像失真的一种方式:

import numpy as np
import cv2 as cv

f_img = 'example.jpg'
im_cv = cv.imread(f_img)

# grab the dimensions of the image
(h, w, _) = im_cv.shape

# set up the x and y maps as float32
flex_x = np.zeros((h, w), np.float32)
flex_y = np.zeros((h, w), np.float32)

# create map with the barrel pincushion distortion formula
for y in range(h):
delta_y = scale_y * (y - center_y)
for x in range(w):
# determine if pixel is within an ellipse
delta_x = scale_x * (x - center_x)
distance = delta_x * delta_x + delta_y * delta_y
if distance >= (radius * radius):
flex_x[y, x] = x
flex_y[y, x] = y
else:
factor = 1.0
if distance > 0.0:
factor = math.pow(math.sin(math.pi * math.sqrt(distance) / radius / 2), -amount)
flex_x[y, x] = factor * delta_x / scale_x + center_x
flex_y[y, x] = factor * delta_y / scale_y + center_y

# do the remap this is where the magic happens
dst = cv.remap(im_cv, flex_x, flex_y, cv.INTER_LINEAR)

cv.imshow('src', im_cv)
cv.imshow('dst', dst)

cv.waitKey(0)
cv.destroyAllWindows()
这与使用ImageMagick的convert -implode函数具有相同的效果。

关于python - 使用Python OpenCV捏缩/凸出变形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64067196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com