Question

Hi I am trying to apply the mobius transformation to an image using matplotlib. This is python code to do this.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from numpy import *


img = mpimg.imread('test.jpg') # load an image
zi = [766j, 512+766j, 256+192j]
wi = [738j, 512+496j, 256+173j]
r = ones((600,700,3),dtype=uint8)*255 # empty-white image
for i in range(img.shape[1]):
    for j in range(img.shape[0]):
        z = complex(i,j)
        qf = ((wi[0] * (-wi[1] * (zi[0]-zi[1]) * (z-zi[2]) + wi[2] * (z-zi[1]) * (zi[0]-zi[2])) - wi[1]*wi[2]*(z-zi[0]) * (zi[1]-zi[2])))
        qs = (wi[2]*(zi[0]-zi[1])*(z-zi[2])-wi[1]*(z-zi[1])*(zi[0]-zi[2])+wi[0]*(z-zi[0])*(zi[1]-zi[2]))
        w = qf/qs
        r[int(imag(w)),int(real(w)),:] = img[j,i,:]

plt.subplot(121)
plt.imshow(img,origin='lower',aspect='auto')
plt.subplot(122)
plt.imshow(r,origin='lower',aspect='auto')
plt.show()

if I run this code, I get the following result. plot

If you see the right side, the size is changed. I want to know the way to fit the result image in the box. The way I did is I hard code the result image size and run the code. However, since the mobius transformation expands and shrink the image, sometimes I get very small image and sometimes I get very big image. Anyone can solve this problem??Thanks!

Was it helpful?

Solution

You can do the following to find the x limits and y limits of your transformed image:

plt.gca().set_aspect('equal')
i, j = np.where(np.all(r!=255, axis=2))
xlimits = j.min(), j.max()
ylimits = i.min(), i.max()
plt.xlim(xlimits)
plt.ylim(ylimits)

the set_aspect() was added to show the image in its original aspect ratio. numpy.where() will find the row and column indices where the image is not white (255, 255, 255), it is taking the minimum and maximum indices to set the new limits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top