Skip to main content
 首页 » 编程设计

python之在 Python 中转换矩形

2024年10月25日8lhb25

我有任何变换矩阵,例如:

sig =[[2,1],[1,1]] 

使用这段代码,我可以变换一个 r=1 的圆:

import numpy as np 
import math as mt 
from matplotlib.pyplot import * 
 
sig =[[2,1],[1,1]] 
 
ndiv=100  
r=1.0 
theta=np.linspace(0,2*np.pi,ndiv) 
x=r*np.cos(theta) 
y=r*np.sin(theta)     
 
fig = figure() 
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) 
ax.plot(x,y,'b.') 
 
x_transf=np.zeros(ndiv) 
y_transf=np.zeros(ndiv) 
 
direc=np.zeros(ndiv) 
 
N=np.zeros(ndiv) 
 
v=[0.0,0.0] 
w=[0.0,0.0]   
for i in range(ndiv):  
    v[0]=x[i] 
    v[1]=y[i] 
 
    w=np.dot(sig,v)      
 
    x_transf[i]=w[0]  
    y_transf[i]=w[1] 
 
 N[i]=mt.sqrt(x_transf[i]**2+y_transf[i]**2) 
 
 
 ax.plot(x_transf,y_transf,'g+') 
 axis('equal') 
 grid('on') 

现在我需要使用这个变换矩阵来变换一个矩形(正方形):

M = [[sqrt(th), -1.5*th],[2*sin(th),cos(th)]] #th is an angle between 0 and 2pi 

同时找到产生最大面积的角度。我怎样才能做到这一点?

请您参考如下方法:

这是一个如何应用转换的示例。作为示例和检查,我还应用了正常旋转(红色):

import matplotlib.pyplot as plt 
import numpy as np 
from numpy import sin, cos, sqrt, pi 
 
r0 = np.array([[.5, .2], [1.5,.2], [1.5,1.2], [.5,1.2], [.5,.2]]) 
 
th = .05*pi 
R = np.array([[cos(th), -sin(th)], [sin(th), cos(th)]]) 
M = np.array([[sqrt(th), -1.5*th],[2*sin(th),cos(th)]]) 
 
r1 = R.dot(r0.T).T 
r2 = M.dot(r0.T).T 
 
plt.plot(r0[:,0], r0[:,1], "bo-") 
plt.plot(r1[:,0], r1[:,1], "ro-") 
plt.plot(r2[:,0], r2[:,1], "go-") 
plt.xlim(-0.2, 1.8) 
plt.ylim(-0., 2.) 
 
plt.show() 

至于找到最大面积,您可以通过分析推导,或者通过数值计算旋转矩形的面积并将其最大化,例如使用 scipy.optimize。 .