我尝试在Python中对图像进行旋转扭曲。但是没有得到预期的输出。互联网上的所有解决方案都使用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()
我期望图像旋转,但输出与输入相同。
答案 0 :(得分:0)
您可以通过这种方式解决它...
# -*- 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.closeAllWindow()