How to vectorize moving window across an image?

8 views (last 30 days)
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;
zScoreMatrix(i,j) = zScore;

Accepted Answer

Image Analyst
Image Analyst on 16 Sep 2022
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, []);
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, []);
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, []);
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, []);
title('Z Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
  1 Comment
Sonicflash on 16 Sep 2022
I followed through your demo, and it worked great. I didn't know of impixelinfo before, either.
Thank you kindly. Really appreicate it.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by