Problem incorporating a Python image filter in Matlab

조회 수: 6 (최근 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 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