MATLAB: How to centering an binary image

avibinary imagecenteringimshowvideo to image

Hello.
I want to convert video to binary images using this code. Before that,
clear all
close all
%// read the video:
reader = VideoReader('shahar_jack.avi');
vid = {};
while hasFrame(reader)
vid{end+1} = im2single(readFrame(reader));
end
%// simple background estimation using mean:
bg = mean( cat(4, vid{:}), 4);
%// estimate foreground as deviation from estimated background:
fIdx = 1; %// do it for frame 43
fg1 = sum( abs( vid{fIdx} - bg ), 3 ) > 0.25;
fg2 = imresize(fg1, 0.5);
figure;
subplot(141); imshow( bg );
subplot(142); imshow( vid{fIdx} );
subplot(143); imshow( fg2 );
And I want to centering each binary image like this demo. How can I mix two code?
% Demo to shift a region in a binary image.
% By ImageAnalyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 14;
grayImage = peaks(200);
imshow(grayImage, []);
subplot(2,2,1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
axis on;
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]); % Maximize figure.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% imtool(z)
binaryImage = grayImage > 5;
subplot(2,2,2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);
axis on;
% Find the centroid of that binary region
measurements = regionprops(binaryImage, 'Centroid')
[rows columns] = size(binaryImage);
rowsToShift = round(rows/2- measurements.Centroid(2))
columnsToShift = round(columns/2 - measurements.Centroid(1))
% Call circshift to move region to the center.
shiftedImage = circshift(binaryImage, [rowsToShift columnsToShift]);
subplot(2,2,3);
imshow(shiftedImage, []);
title('Shifted Binary Image', 'FontSize', fontSize);
axis on;

Best Answer

Hi,
From the two piece of codes I see you need to create a for loop for fIdx from 1 to 43 and then give each fg2 matrix calculated to the grayImage in the next piece of code and remove grayImage = peaks(200);
grayImage=fg2;
Full second piece of code will come in for loop. Note that you need to remove unnecessary imshow in between to not be plotting every image.