2016-03-16 2 views
1

Я пытаюсь преобразовать некоторый MatLab код на Python3, но у меня возникают проблемы с одной линией, линия в MatLab являетсяКак использовать «XData» в imshow() из MatLab в Python3 imshow()

imshow(sqrt(I),[0,100],'InitialMagnification','fit','xdata',[-1,1]*a,'ydata',[-1,1]*a); 

Где a - некоторая константа.

Проблемы, с которыми я столкнулся, связаны с 'XData' и 'YData'. Я в настоящее время, используя код Python

matplotlib.pyplot.imshow(np.sqrt(np.real(I)), vmin = 0, vmax = 100) 

Как конвертировать 'XData' и 'YData' элементов в Python?

EDIT Полный код для Python и MatLab

Python код:

(я ооочень жаль, но я не комментировали этот код еще я могу сделать, если это необходимо)

import numpy as np 
import matplotlib.pyplot as plt 

plt.close("all") 

l = 633*10**(-6) 
L = 10 

N = 2**11 
Nx = 2**11 
Ny = 2**11 

xmax = 5*10**(-4) 
ymax = 5*10**(-4) 
curlyv = np.zeros((Nx,Ny),dtype=np.double) 
x = np.tile(np.linspace(-xmax,xmax,Nx),(Ny,1)) 
y = np.tile(np.linspace(-ymax,ymax,Ny).reshape(Ny,1),(1,Nx)) 
h = np.sqrt(4*np.pi/(l*L)) 

np_x = np.array(x) 
np_y = np.array(y) 

aperture = np.sqrt(np_x**2 + np_y**2) >= 100*10**-6 

curlyv[aperture] = 1  

vprime = np.fft.fftshift(np.fft.fft2(curlyv)) 
I = vprime*np.conj(vprime) 
Imax = np.real(np.amax(I)) 
fig2 = plt.figure() 
Imax_b = Imax/5000 
pltp = plt.imshow(np.sqrt(np.real(I)), vmin = 0, vmax = 100, cmap='Greys_r', extent=(-Nx/h*1000, Nx/h*1000, -Ny/h*1000, Ny/h*1000)) 

plt.show() 

Python изображения:

Python Image

MatLab Код

% This script calculates, via a 2D Fourier Transform, the Fraunhofer diffraction 
% pattern due to a circular aperture. Source plane is the xy-plane. The field plane 
% is at a distance L from the source plane. 

lambda = 633e-6; L = 10;      % meters 

% Set up the source plane domain and initialize the source plane amplitude (curlyv) at each point 
N=2^11; Nx = N; Ny = N;       % resolution (pixels) 
xmax=5e-4;         % meters 
ymax=5e-4;         % meters 
curlyv = zeros(Nx,Ny);      % curlyv has one complex value at each location (x,y) 
x=repmat(linspace(-xmax,xmax,Nx),Ny,1);  % x domain (source plane) 
y=repmat(linspace(-ymax,ymax,Ny)',1,Nx); % y domain (source plane) 
h = sqrt(4*pi/(lambda*L));     % axes scaling (from the theory) 

% construct a logical vector corresponding to the (x,y)-locations where the incident field is 
% non-zero. Only need to set these elements of curlyv so some non-zero values 
% corresponding to the incident field's complex amplitude. 

aperture = sqrt(x.^2+y.^2) >= 100e-6;  % logical vector giving aperture shape 
% The incident field ampli0tude u(x,y) is just 1 everywhere in the aperture. The additional 
% exponential corresponding to the phase in curlyv is formally required from the theory but can be omitted to a good 
% approximation in most cases. 
curlyv(aperture)=1;       %exp(1i*h^2*(x(aperture).^2+y(aperture).^2)); 

figure(1); 
iptsetpref('ImShowAxesVisible','On'); 
imshow(curlyv,[-0.5 1],'InitialMagnification','fit',... 
    'xdata',[-xmax, xmax]*1000,'ydata',[-ymax,ymax]*1000); % display the diffraction pattern 
vprime = fftshift(fft2(curlyv,Nx,Nx));  % perform the 2D FT to get the field plane field amplitude 
I = conj(vprime).*vprime;     % calculate intensity 
xlabel('mm'); ylabel('mm'); 

figure(2); 
Imax=max(max(I)); 
iptsetpref('ImShowAxesVisible','On'); 
imshow(sqrt(I),[0,sqrt(Imax)/50],'InitialMagnification','fit','xdata',[-1,1]*Nx/h*1000,'ydata',[-1,1]*Ny/h*1000); % display the diffraction pattern 

colormap(bone); shg; shading interp; 
axis([-2,2,-2,2]*1000);  % 0 = black, Imax/10 = white (so many pixels will be saturated) 
xlabel('mm'); ylabel('mm'); 

MatLab Image (что изображения должны выглядеть)

enter image description here

ответ

1

XData for imshow in MATLAB устанавливает

Пределов вдоль оси Х нестандартным пространственной системы координат, указанных в качестве двухэлементный вектор

(аналогично для YData и оси y). Для matplotlib.pyplot.imshow, the extent parameter, кажется, имеет тот же самый эффект:

степень: скаляры (слева, справа, снизу, сверху), опционально, по умолчанию: None

расположение, в данных координатах, низшего левый и верхний правый углы. Если None, изображение расположено так, что пиксельные центры падают на индексы на основе нуля (строки, столбца).

Следовательно, эквивалентный вызов будет

matplotlib.pyplot.imshow(np.sqrt(np.real(I)), vmin = 0, vmax = 100, extent=(-a, a, -a, a)) 
+0

Спасибо за информацию, но XData и ydata должен сделать нечто большее, чем просто изменение «осей» образом (я думаю), как изображение, которое я получить от python с или без степени это то же самое, что и изображение, которое я получаю из MatLab, когда НЕ использует xdata, ydata, но с расширением в Python, я не получаю то же изображение, что и MatLab. Я проверил все переменные, которые я использую в Python, такие же, как в MatLab. Я не хочу слишком беспокоиться, но есть ли у вас какие-то другие идеи? – John

+0

@John Я исправил свою опечатку (минус в неправильном месте). Если это не поможет вам, вы можете отредактировать сообщение, чтобы показать фактические данные и результаты?(он, похоже, дает тот же результат с 'extent' и' XData'/'YData' здесь, кроме' imshow' делает 'axes' невидимым, а pyplot не делает) – zeeMonkeez

+0

Я видел проблему со знаками и исправил это. Я отредактировал главный пост с кодом и выходом. – John

Смежные вопросы