Skip to content

Instantly share code, notes, and snippets.

@mountain
Last active September 16, 2021 06:37
Show Gist options
  • Save mountain/39ff72522cfc122cf5b257e90702302a to your computer and use it in GitHub Desktop.
Save mountain/39ff72522cfc122cf5b257e90702302a to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
# constructing an image with a frame in the center
img = np.zeros([255, 255], dtype=np.int)
img[64:192, 64] = np.ones([128], dtype=np.int) * 255
img[64:192, 192] = np.ones([128], dtype=np.int) * 255
img[64, 64:192] = np.ones([128], dtype=np.int) * 255
img[192, 64:192] = np.ones([128], dtype=np.int) * 255
cv2.imwrite('orig.png', img)
# complex transformation
def transform(z):
result = 0
for t in np.linspace(0.0, 1.0, 100):
ratio = np.exp(-t)
phi = 2 * np.pi * t
w = np.cos(phi) + np.sin(phi) * 1j
result += ratio * w * z / 12.5
return result
# transform image
def grid_sample(img, w):
t1 = np.zeros(w.shape, dtype=np.int)
t2 = np.zeros(w.shape, dtype=np.int)
grid = (128 + 128j) + 128 * w
tx = np.round(np.real(grid)).astype(np.int)
ty = np.round(np.imag(grid)).astype(np.int)
t1[ty, tx] = img
tx = np.round(np.real(grid) + 0.5).astype(np.int)
ty = np.round(np.imag(grid) + 0.5).astype(np.int)
t2[ty, tx] = img
return np.max(np.array([t1, t2]), axis=0)
# apply transformation
def apply(img, trans):
x, y = np.meshgrid(np.linspace(-1.0, 1.0, 255), np.linspace(-1.0, 1.0, 255))
z = x + 1j * y
img = img + grid_sample(img, trans(z))
img = img + grid_sample(img, trans(z))
img = img + grid_sample(img, trans(z))
img = img + grid_sample(img, trans(z))
img = img + grid_sample(img, trans(z))
img = img + grid_sample(img, trans(z))
img = img + grid_sample(img, trans(z))
img = img + grid_sample(img, trans(z))
return img
cv2.imwrite('result.png', apply(img, transform))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment