图像转换python

我正在尝试使用 Python 创建类似于下图所示的效果:

我的想法是创建一个空白图像并将输入图像中的像素映射到输出图像中每个位置的适当像素(即反向映射)。

我正在考虑使用极坐标形式的像素位置并调整每个像素的角度。我尝试创建一个“偏移”变量来模拟每次迭代都会增加值的阿基米德螺线,但这并没有给出所需的输出。

任何人都可以帮助我构建我当前的代码并提出一种功能/方法来在输出图像上实现所需的效果吗?

def cart2pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    return(rho, phi)

def pol2cart(rho, phi):
    x = rho * np.cos(phi)
    y = rho * np.sin(phi)
    return(x, y)

def raster2cart(y, x, center):
    x = x - center[1]
    y = center[0] - y
    return x, y

def cart2raster(y, x, center):
    x+= center[1]
    y = center[0] - y
    return x, y

def effect(img, center, r):
    img_output = np.zeros(img.shape, dtype=img.dtype)
    for row in range(len(img_output[0])):
        for col in range(len(img_output[1])):
            x, y = raster2cart(col, row , center)
            if x**2 + y**2 <= r**2:
                rho, phi = cart2pol(x,y)
                ### DO SOMETHING
                x, y = pol2cart(rho, phi)
                x, y = cart2raster(y, x, center)
                img_output[row, col] = img[int(x), int(y)]
            # else:
            #   img_output[row, col] = img[int(row), int(col)]
            
    return img_output

cv2.imshow('Input', img)
cv2.imshow('Out', effet(img))
cv2.waitKey(0)

回答

由于您使用的是 opencv,因此请使用remap来执行此操作,因为它可以为您处理插值。

至于转换,看起来是一个螺旋,所以,我尝试在下面的代码中生成一个阿基米德一般螺旋。希望我做对了,但如果有任何错误,请纠正。

您可以调整参数 a、b 和 c 来控制变换。

im = cv.imread("flower.jpg")

# parameters controlling the transform
# (cx, cy) is the center, here I'm using the mid point, but you can use other values
cx = im.shape[1]/2
cy = im.shape[0]/2
# a, b and c are General Archimedean spiral parameters
a = -1
b = 2
c = 1
# select the region around (cx, cy) to apply the transform
r = 1

x = np.linspace(0, im.shape[1], im.shape[1], dtype=np.float32)
y = np.linspace(0, im.shape[0], im.shape[0], dtype=np.float32)
xv, yv = np.meshgrid(x - cx, y - cy)

mag, ang = cv.cartToPolar(xv, yv)
nmag = cv.normalize(mag, None, norm_type=cv.NORM_MINMAX)

sxv, syv = cv.polarToCart(mag, (ang + (a + b*np.pi*nmag**(1.0/c))*(nmag < r)))
spiral = cv.remap(im, 
         sxv + cx, 
         syv + cy, 
         cv.INTER_LINEAR)

输入:

输出:

center 是图像中心:

中心是 (300, 300):


以上是图像转换python的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>