首页 > 解决方案 > Python中的变形

问题描述

我尝试按照此链接对图像进行变形

https://github.com/aydal/Cylinderical-Anamorphosis/blob/master/anamorph.py

它给出了一个变形的图像,但它给出了半圆形的图像。但我想要一个完整的圆圈大小的输出。我试过了

warp[c-j, i-1] = img[p-1, q-1]
warp[c+j, i-1] = img[p-1, q-1]

代替warp[c-j, i-1] = img[p-1, q-1]

但它不会在整个圆圈中给出一张图像,而是两次创建相同的输出!

谁能帮帮我吗。

完整代码:

import math
from cv2 import *
import numpy as np

img = imread("test.jpg")
(rows, cols) = (img.shape[0], img.shape[1])
r = 0  #offset-gives space to keep cylinder and height of the image from bottom: original: math.trunc(.25*rows)
c = rows  #this will be the decisive factor in size of output image-maximum radius of warped image: original: c = r+rows
warp = np.zeros([c,2*c,3], dtype=np.uint8)


def convert(R, b):
    return math.trunc(b*rows/(2*math.asin(1))), math.trunc(c-R)


for i in range(0, 2*c):
    for j in range(1, c):
        b = math.atan2(j, i-c)
        R = math.sqrt(j*j+math.pow(i-c, 2))
        if R>=r and R<=c:
            (q, p) = convert(R, b)
            warp[c-j, i-1] = img[p-1, q-1]
            #warp[c+j, i-1] = img[p-1, q-1]

imshow("Output", warp)
waitKey()

原始图像在此处输入图像描述

我的输出图像(半圈)在此处输入图像描述

所需的输出图像在此处输入图像描述

标签: pythonimage-processingcylindricalanamorphism

解决方案


与列偏移量类似,您应该在计算b和时包括行的偏移量R。由于扭曲的图像具有c行,因此偏移量为c//2

b = math.atan2(j - c//2, i-c)
R = math.sqrt((j - c//2)**2 + math.pow(i-c, 2))

请注意,扭曲的图像不是一个完美的圆形,因为您指定它的宽度是高度的两倍。如果你想要一个完整的圆圈,你还应该调整上边界检查,R因为c//2这是最大值。沿行的半径:

if r <= R <= c//2:
    ...

同样,您需要调整计算convert

return ..., math.trunc(c//2 - R)

但是,在任何情况下,您都可以从一开始就使用方形图像,即指定warp.shape == (c, c).

编辑

更新的代码,使用原始尺寸的扭曲图像:

import math
import cv2
import numpy as np

img = cv2.imread("/tmp/img.jpg")
(rows, cols) = (img.shape[0], img.shape[1])
r = 0
c = rows // 2
warp = np.zeros([rows, cols, 3], dtype=np.uint8)


def convert(R, b):
    return math.trunc(c * (1 - b/math.pi)), 2*math.trunc(c - R) - 1


for i in range(0, cols):
    for j in range(0, rows):
        b = math.atan2(j - c, i - c)
        R = math.sqrt((j - c)**2 + (i - c)**2)
        if r <= R <= c:
            q, p = convert(R, b)
            warp[j, i] = img[p, q]

cv2.imshow("Output", warp)
cv2.waitKey()

并输出图像:

输出图像


推荐阅读