How to vectorize moving window across an image?

Hello,
I am trying to learn faster image processing techniques. I currently have implemented a double for loop that calculates a z-score and "throw away" the value if it is too close to the mean.
One option I considered was using a par for loop, but from my understanding, implementation using vectorization is a faster/better practice.
Here is the snippet of what I am trying to do:
inFrame = imread('Lenna.png');
% Convert frame into grayscale, use standard NTSC Conversion
grayFrame = 0.2989*inFrame(:,:,1) + 0.5870*inFrame(:,:,2) + 0.1140*inFrame(:,:,3);
[height, width, colormap] = size(grayFrame);
% Preallocate for window matrix
windowSize = 5;
window = zeros(windowSize);
zScoreMatrix = zeros(size(grayFrame));
% Begin moving window across image
for i = 3:height-2
for j = 3:width-2
window = grayFrame(i-2:i+2,j-2:j+2);
window = double(window);
mean = mean2(window);
std_dev = std2(window);
zScore = (window(3,3) - mean)/std_dev;
if abs(window(3,3) - mean) < 3
zScoreMatrix(i,j) = 0;
else
zScoreMatrix(i,j) = zScore;
end
end
end

 채택된 답변

Image Analyst
Image Analyst 2022년 9월 16일

0 개 추천

Try using imfilter and stdfilt
% Demo by Image Analyst
% Initialization Steps.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 18;
markerSize = 40;
grayFrame = imread('cameraman.tif');
% Display the image.
subplot(2, 2, 1);
imshow(grayFrame, []);
impixelinfo;
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Blur the image.
windowSize = 5;
kernel = ones(windowSize) / windowSize^2;
blurredImage = double(imfilter(grayFrame, kernel, "replicate"));
% Display the image.
subplot(2, 2, 2);
imshow(blurredImage, []);
impixelinfo;
title('Blurred Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Get the standard deviation of the image.
stdDevImage = stdfilt(grayFrame, ones(windowSize));
% Display the image.
subplot(2, 2, 3);
imshow(stdDevImage, []);
impixelinfo;
title('Standard Deviation Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Compute the z score.
zScoreMatrix = (double(grayFrame) - blurredImage) ./ stdDevImage;
% Display the image.
subplot(2, 2, 4);
imshow(zScoreMatrix, []);
impixelinfo;
title('Z Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');

댓글 수: 1

I followed through your demo, and it worked great. I didn't know of impixelinfo before, either.
Thank you kindly. Really appreicate it.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Image Processing Toolbox에 대해 자세히 알아보기

제품

릴리스

R2020a

질문:

2022년 9월 16일

댓글:

2022년 9월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by