Problem incorporating a Python image filter in Matlab

7 ビュー (過去 30 日間)
Richard Ott
Richard Ott 2020 年 9 月 23 日
コメント済み: Richard Ott 2020 年 9 月 25 日
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')
  1 件のコメント
Richard Ott
Richard Ott 2020 年 9 月 25 日
I think I was just having Python version compabilit issues. That I resovled now.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCall Python from MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by