How to convert Python code into matlab

I have a Python code.how can I convert it into matlab code or is there any option of executing the same using matlab

5 Comments

%% Fractional Leaky Integrate-and-Fire Model
% Model files for the paper
% Wondimu Teka, Toma M.Marinov, Fidel Santamaria (2014) Neuronal Spike Timing Adaptation Described with a Fractional Leaky Integrate-and-Fire Model.
% PLoS Comput Biol 10(3): e1003526. doi:10.1371/journal.pcbi.1003526
clear
rseed=2342;
Ncells=1; %number of cells, do not change this value, this code is not for network, it is only for one cell.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters values that can be varied.
dt=0.1; %ms time step. This value is used for all the data.
t=0:dt:1000; %ms mostly is up to 5000 ms (5sec) or 10000 ms (10 sec) is used.
% alpha= ??; % the fractional exponent (order) it is varied below using a for loop
Rm=40; %Mohms
taum=20*ones([1 Ncells]); %ms membrane time constant
Cm=0.5; %nF % this is not used since taum and Rm are used and note taum = Cm*Rm
refrac=8*ones([1 Ncells]); %ms absolute refarctory period
v0= -70*ones([1 Ncells]); % mV initial value
% initial voltage was varied: used values are v0= -70, v0= -75 v0= -58, v0= -45,
vrest= -70; % mV the resting potential which is used for reset too.
vth= vrest + 20*ones([1 Ncells]); % is -50 mV, threshold value of membrane voltage
vpeak = vrest + 100*ones([1 Ncells]); % is 30 mV, peak value of he voltage at spike
Iinjamplitude= 3; % nA injected current amplitude, see Iinj for the whole injected current
% for the subthershold use Iinjamplitude= 0.3;
Namp=0; %noise amplitude, to add white Gaussian noise with this standard devation Namp, which is noise amplitude
% This value should be changed only for figure 11,
% Namp=1 % For only figure 11,
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% used for most of the simulations
Iinj=Iinjamplitude*ones(length(t),Ncells)+ Namp*(randn(length(t),Ncells));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the sinusoidal simulation with non constant freqency, use the following ZAP current
% f=0.1*(2./(1+exp(-t./1500))-1).^3; % frequency in cycle per ms. since time is in ms; the freqency increases from 0 Hz to 100 Hz
% Iinj=0.3*sin((2*pi).*f.*t)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for figure 10 use the following current instead of the above
% for the sinusoidal simulation with constant freqency, use the following
%f = 0.003 % this is in cycle per ms, it is the same is 3 Hz
%Iinj= 2 +2*sin((0:dt:t(end)).*2*pi*f)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% names for parameters to pass them to the main function: runNetworkderivative
NetProp.Ncells=Ncells;
NetProp.Rm=Rm; %Mohms
NetProp.TauM=taum;
NetProp.Cm=Cm; %nF % this is not used since taum and Rm are used.
NetProp.Refrac=refrac;
NetProp.vTh=vth;
NetProp.v0=v0;
NetProp.vrest=vrest;
NetProp.vpeak=vpeak;
NetProp.Noise=Namp;
NetProp.dt=dt;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Main integrator
% Integrating output for different alpha values using the fractional derivative
b=1;
for alpha=1:-0.2:0.2
out(b)=runNetworkderivative(NetProp,Iinj,t,rseed,alpha); % main output
% Note:This has the following output out.v=v for voltage; out.sp=sp for spike ; out.Memo2=Memo2 for memery; out.t=t for time;
alphavalue(b)=alpha
ISI{b}=diff(out(b).t(logical(out(b).sp(1:end-1)))); % calculates ISI in msec
firingrate{b} = 1000./ISI{b}; %in Hz, calculates firing rate
totalspike(b) = sum(out(b).sp); % for toltal number of spikes for total time
b= b+1
end
cv=['kbgmr'];
c=1;
for b=1:length(out) % for alpha =1.0
subplot(5,1,c)
trange=1:1000/dt;
plot(out(b).t(trange), out(b).v(trange), cv(b), 'Linewidth',1.5) %
set(gca, 'FontSize', 14, 'FontName', 'Helvetica')
set(gca, 'LooseInset', get(gca,'TightInset'))
ylabel('V (mV)', 'fontsize',14, 'FontName', 'Helvetica');
legendinfo2= sprintf('\\alpha= %0.1f\n', alphavalue(b));
c=c+1;
axis([-1 1000 -75 35])
legend(legendinfo2,'Location','SouthWest', 'fontsize',11, 'FontName', 'Helvetica')
clear legendinfo2;
end
xlabel('Time (ms)', 'fontsize',14, 'FontName', 'Helvetica');
@Suresh, now that your code is properly formatted, can you explain what this has to do with this question?
import cv2
import numpy as np
class ContrastMeasures():
def __init__(self):
pass
def fm(self, img, fm_name, window_size=3, threshold=7):
"""
applies focus measure fm_name to input image img
fm_name must be one of the following:
'SML', 'CMSL', 'GLV', 'TENENGRAD1', 'JAEHNE'"""
if fm_name == 'SML':
return self.SML(img, window_size, threshold)
elif fm_name == 'CMSL':
return self.CMSL(img, window_size)
elif fm_name == 'GLV':
return self.GLV(img, window_size)
elif fm_name == 'TENENGRAD1':
return self.tenengrad1(img, window_size, threshold)
elif fm_name == 'JAEHNE':
return self.jaehne(img, window_size)
def CMSL(self, img, window):
"""
Contrast Measure based on squared Laplacian according to
'Robust Automatic Focus Algorithm for Low Contrast Images
Using a New Contrast Measure'
by Xu et Al. doi:10.3390/s110908281
window: window size= window X window"""
ky1 = np.array(([0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]))
ky2 = np.array(([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0]))
kx1 = np.array(([0.0, 0.0, 0.0], [-1.0, 1.0, 0.0], [0.0, 0.0, 0.0]))
kx2 = np.array(([0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]))
g_img = abs(cv2.filter2D(img, cv2.CV_32F, kx1)) + \
abs(cv2.filter2D(img, cv2.CV_32F, ky1)) + \
abs(cv2.filter2D(img, cv2.CV_32F, kx2)) + \
abs(cv2.filter2D(img, cv2.CV_32F, ky2))
return cv2.boxFilter(
g_img * g_img,
-1,
(window, window),
normalize=True)
def SML(self, img_in, window_size, threshold):
"""
Sum of modified Laplacian according to
'Depth Map Estimation Using Multi-Focus Imaging'
by Mendapara
"""
# kernels in x- and y -direction for Laplacian
ky = np.array(([0.0, -1.0, 0.0], [0.0, 2.0, 0.0], [0.0, -1.0, 0.0]))
kx = np.array(([0.0, 0.0, 0.0], [-1.0, 2.0, -1.0], [0.0, 0.0, 0.0]))
# add absoulte of image convolved with kx to absolute
# of image convolved with ky (modified laplacian)
ml_img = abs(cv2.filter2D(img_in, cv2.CV_32F, kx)) + \
abs(cv2.filter2D(img_in, cv2.CV_32F, ky))
# sum up all values that are bigger than threshold in window
ret, img_t = cv2.threshold(ml_img, threshold, 0.0, cv2.THRESH_TOZERO)
return cv2.boxFilter(
img_t,
-1,
(window_size, window_size),
normalize=False)
def GLV(self, img, window_size=3):
"""
Gray Level Variance according to
'Depth Map Estimation Using Multi-Focus Imaging'
by Mendapara
"""
# calculate mean for each window
mean = cv2.boxFilter(
img,
cv2.CV_32F,
(window_size, window_size),
normalize=True)
# return variance=(img[x,y]-mean[x,y])^2
return (img - mean)**2.0
def tenengrad1(self, img, window_size, threshold):
"""
Tenengrad2b: squared gradient absolute thresholded and
summed up in each window
according to
'Autofocusing Algorithm Selection in Computer Microscopy'
by Sun et Al.
"""
# calculate gradient magnitude:
S = cv2.Sobel(img, cv2.CV_32F, 1, 0, 3)**2.0 + \
cv2.Sobel(img, cv2.CV_32F, 0, 1, 3)**2.0
# threshold image
ret, dst = cv2.threshold(S, threshold, 0.0, cv2.THRESH_TOZERO)
# return thresholded image summed up in each window:
return cv2.boxFilter(
dst,
-1,
(window_size, window_size),
normalize=False)
def jaehne(self, img, window_size):
"""Only implemented for window_size 3 or 5 according to
'Entwicklung einer fokusbasierenden Hoehenmessung mit
dem "Depth from Focus"-Verfahren' by Dunck
"""
if window_size == 3:
kernel = np.array([
[1.0, 2.0, 1.0],
[2.0, 4.0, 2.0],
[1.0, 2.0, 1.0]])
sum = 16
elif window_size == 5:
kernel = np.array([
[1.0, 4.0, 6.0, 4.0, 1.0],
[4.0, 16.0, 24.0, 16.0, 4.0],
[6.0, 24.0, 36.0, 24.0, 6.0],
[4.0, 16.0, 24.0, 16.0, 4.0],
[1.0, 4.0, 6.0, 4.0, 1.0]])
sum = 256
img_t = (img - cv2.filter2D(img, cv2.CV_32F, kernel) / sum)**2
return cv2.filter2D(img_t, -1, kernel) / sum
  • © 2021 GitHub, Inc.
Vombarelli Neha Please, didi you find the solution to this problem?
import numpy as np
impot matplotlib.pyplot as plt
line=np.linspace(-5,5,1000)
#plt.plot(line,np.tanh(line), label=''tanh'')
#plt.plot(line,np.maximum(line,0), label=''sigmoid'')
plt.plot(line,1/(1+np.exp(-line)),label=''sigmoid'')
plt.legend(loc=''best'')
plt.xlabel(''z'')
#plt.ylabel(''Relu(x),tanh(x), sigmoid(x)'')
plt.ylabel(''sigmoid(z)'')

Sign in to comment.

Answers (4)

Rik
Rik on 24 Aug 2018
See this, or with system('python python_script.py');
This was the top result for my Google search: link

5 Comments

The code above only executes the python code in matlab but if you want to use all matlab capabilities such as the debug part (debugging python code in matlab) the system function is not an option.
I believe Vombarelli Neha said that "he or she" wants to "convert" not "call" !
Read on: "I have a Python code.how can I convert it into matlab code or is there any option of executing the same using matlab".
Anyway, a strict convert is theoretically possible (since both languages are Turing-complete), although this conversion is probably either not automatic, or not effecicient. You should either re-write it completely in Matlab, or run it as Python code. Unless you find/write a good Python2Matlab function, I know there are surprisingly good converters sometimes.
import numpy as np
impot matplotlib.pyplot as plt
line=np.linspace(-5,5,1000)
#plt.plot(line,np.tanh(line), label=''tanh'')
#plt.plot(line,np.maximum(line,0), label=''sigmoid'')
plt.plot(line,1/(1+np.exp(-line)),label=''sigmoid'')
plt.legend(loc=''best'')
plt.xlabel(''z'')
#plt.ylabel(''Relu(x),tanh(x), sigmoid(x)'')
plt.ylabel(''sigmoid(z)'')

Sign in to comment.

Gautam Takoo
Gautam Takoo on 21 Jan 2022
Edited: Gautam Takoo on 21 Jan 2022
I have a Python code.how can I convert it into matlab code or is there any option of executing the same using matlab
import cv2
from PIL import Image
import numpy as np
from glob import glob
import os
def main():
# path of the folder containing the raw images
inPath =("Z://Randomimages")
# path of the folder that will contain the modified image
outPath =("Z:/normaltogray")
for files in os.walk(inPath):
for imagePath in os.listdir(inPath):
if not imagePath.endswith(".jpg"):
print("{} file is not an expected file".format(imagePath))
continue
inputPath = os.path.join(inPath, imagePath)
img = np.array(Image.open(inputPath))
if imagePath.startswith('T1_E1'):
roi = img[1360:1470,850:2700]
elif imagePath.startswith('T1_E2'):
roi= img[1370:1450,920:2770]
gray=cv2.cvtColor(roi,cv2.COLOR_BGR2GRAY)
fullOutPath = os.path.join(outPath,imagePath)
cv2.imwrite(fullOutPath,gray)
print(fullOutPath)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Driver Function
if __name__ == '__main__':
main()
#

2 Comments

If you didn't bother reading my answer, why should I bother responding to your question?

Sign in to comment.

This may help you. There are a number of ducoments and videos related to using MATLAB with Python.
def Lagrange(x, y, n, xx):
sum = 0
for i in range(0, n + 1):
product = y[i]
for j in range(0, n + 1):
if (i != j):
product = product * (xx - x[j]) / (x[i] - x[j])
sum += product
return sum
def Trapezoidal(h, n, f):
sum = f[0]
for i in range (1, n):
sum = sum + 2 * f[i]
sum = sum + f[n]
ans = h * sum / 2
return ans

Products

Release

R2017b

Asked:

on 24 Aug 2018

Commented:

on 21 Oct 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!