Problem incorporating a Python image filter in Matlab

6 次查看(过去 30 天)
Hi,
I'm trying to run a python median filter in Matlab (because Matlab does not have a good tool to omit nan's in large window median filters).
Below is the code I'm running as a test. It runs but the output from the python medianfilter is incorrect (if you run the code and look at the plots you'll notice). I suppose the problem might be in the way the inital array needs to be turned into a vector and reshaped back to its original shape again. This needs to be done because numpy.array won't convert a matlab matrix directly. But I am unable to pick the exact problem here. Maybe someone can help?
% load modules
py.importlib.import_module('silx');
py.importlib.import_module('numpy');
I = imread('ngc6543a.jpg'); % load image
I = I(:,:,3); % keep only one layer of the image as test
Im = medfilt2(I,[20,20]); % matlab median filter
I = double(I); % convert to double top np-array
npI = py.numpy.array(I(:).'); % convert to np-array --> vector
Ishape = py.tuple({uint16(size(I,1)), uint16(size(I,2))}); % tuple of original matrix shape
npI = py.numpy.reshape(npI, Ishape,'C'); % reshape the matrix back to original
pyIm = py.silx.math.medianfilter.medfilt(npI,uint8(21),0); % apply median filter
pyIm = double(pyIm); % convert back to matlab array
% plot and compare results
subplot(2,2,1)
imagesc(I)
title('original image')
subplot(2,2,2)
imagesc(Im)
title('matlab filter')
subplot(2,2,3)
imagesc(pyIm)
title('python filter')

采纳的回答

Kojiro Saito
Kojiro Saito 2020-9-24
I'm not sure about "numpy.array won't convert a matlab matrix directly", but py.numpy.array(I) works fine, so I don't think it's need to create a vector and reshape.
The following modified code will work fine.
% load modules
py.importlib.import_module('silx');
py.importlib.import_module('numpy');
I = imread('ngc6543a.jpg'); % load image
I = I(:,:,3); % keep only one layer of the image as test
Im = medfilt2(I,[20,20]); % matlab median filter
I = double(I); % convert to double top np-array
npI = py.numpy.array(I); % convert to np-array
npI2 = npI.copy(); % copy np-array to avoid "must be a C_CONTIGUOUS numpy array" error
pyIm = py.silx.math.medianfilter.medfilt(npI2,uint8(21),0); % apply median filter
pyIm = double(pyIm); % convert back to matlab array
% plot and compare results
subplot(2,2,1)
imagesc(I)
title('original image')
subplot(2,2,2)
imagesc(Im)
title('matlab filter')
subplot(2,2,3)
imagesc(pyIm)
title('python filter')

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by