-1

I tried twirl transformation on image in Python. But not getting the expected output. All the solutions on the internet are in C#.

import cv2
import math
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

img = cv2.imread('lena.jpg')
img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("input",img_gray)
imgcopy=img_gray.copy()

rmax,alpha,xc,yc=input("enter rmax alpha center respectively: ").split()
rmax=float(rmax)
alpha=float(rmax)
xc=float(rmax)
yc=float(rmax)
for x in range(img_gray.shape[0]):
    for y in range(img_gray.shape[1]):
        fie=math.radians(alpha)
        xdiff=x-xc
        ydiff=y-yc
        r=math.sqrt(math.pow(xdiff,2)+math.pow(ydiff,2))
        if r>rmax:
            nx=x
            ny=y
        else:
            angle=math.atan2(ydiff,xdiff)+fie*((rmax-r)/rmax)
            nx=round(xc+r*math.cos(angle))
            ny=round(yc+r*math.sin(angle))
            imgcopy[nx][ny]=img_gray[x][y]

cv2.imshow("output",imgcopy)       
cv2.waitKey(0)
cv2.destroyAllWindows()

I am expecting a twirled image, but getting output as same as input.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sadia_30
  • 11
  • 1
  • As a newbie, you should not be writing this code. This is _not_ a trivial problem. – DYZ Mar 26 '19 at 06:29
  • Your title says you are getting an error, but the main body of your question says your input is the same as your output. Those explanations of your problem do not match - which is correct? – halfer Mar 27 '19 at 20:57

1 Answers1

0

You can solve it in this way...

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 16:46:20 2019

@author: Hafiz
"""

import cv2
import numpy as np
import math

imgIn=cv2.imread('lena.jpg',0)
imgOut=np.zeros(imgIn.shape,dtype='uint8')

alpha=float(input('Enter alpha: '))
alpha=np.deg2rad(alpha)
rmax=int(input('Enter rmax: '))

centerX=int(imgIn.shape[1]/2)
centerY=int(imgIn.shape[0]/2)

for i in  range(imgOut.shape[0]):
    for j in range(imgOut.shape[1]):
        dX=j-centerX
        dY=i-centerY
        r=math.sqrt(dX*dX+dY*dY)
        if(r<=rmax):
            beta=math.atan2(dY,dX)+alpha*((rmax-r)/rmax)
            x=round(centerX+r*math.cos(beta))
            y=round(centerY+r*math.sin(beta))
        else:
            x=j
            y=i
        if(x>=imgIn.shape[1] or y>=imgIn.shape[0] or x<0 or y<0):
            imgOut.itemset((i,j),0)
        else:
            imgOut.itemset((i,j),imgIn.item(y,x))
cv2.imshow('in',imgIn)       
cv2.imshow('out',imgOut)
cv2.waitKey(0)
cv2.destroyAllWindows()
hafiz031
  • 2,236
  • 3
  • 26
  • 48