How to use FinalImage variable inside parfor Loop?

78 views Asked by At

I am trying to segment an image of (512 x 512) into 4 segments of (128 x 128) images having the upper row of the orignal image. Then trying to run parallel parfor loop on it. But unable to do so. Here is my code.

FinalImage = ones(512,512);
%visiblity function initialization, see equation (4)

parfor imageSegment = 1:8;  

     img = double(imread([filename '.jpg']))./255;
     img = im2bw(img);

    if imageSegment == 1
     img = img(1:128,1:128);
    [nrow, ncol] = size(img);
    elseif imageSegment == 2
     img = img(1:128,129:256);
     [nrow, ncol] = size(img);
    elseif imageSegment == 3
     img = img(1:128,257:384);
     [nrow, ncol] = size(img);
    elseif imageSegment == 4
     img = img(1:128,385:512);
     [nrow, ncol] = size(img);

for nMethod = 3:3;

//Some code

end
end

 imwrite(FinalImage, gray(256), [filename '_FinalImage_' num2str(nMethod) '.bmp'], 'bmp');

fprintf('close');

How to use FinalImage variable inside the parfor loop ??

1

There are 1 answers

2
hmofrad On BEST ANSWER

To extract all 16 segments (of size 128*128) of a 512*512 image in a parallel way, you may want to try the following code:

clear;
clc

% #1 image from dataset of standard 512X512 grayscale test images
% Availabe online at http://decsai.ugr.es/cvg/CG/base.htm
img = imbinarize(imread('http://decsai.ugr.es/cvg/CG/images/base/1.gif'));

d = 512; % Needs to be a power of 2
n = 4;   % Needs to be a power of 2
s = d/n;
tmp = zeros(s, s);
ind = 1:s:d;

% parpool(numel(ind))
disp('Process')
tic

parfor i = 1:numel(ind)
    j = ind(mod(i,n)+1);
    for k = 0:n-1
        l = ind(mod(k,n)+1);
        tmp = img(j:j+s-1, l:l+s-1);
        imwrite(tmp,[num2str((i*n)+1+k),'.jpg'])
    end
end

toc
disp('done')

The result would be 16 images in the following order:

01.jpg | 02.jpg | 03.jpg | 04.jpg
05.jpg | 06.jpg | 07.jpg | 08.jpg
09.jpg | 10.jpg | 11.jpg | 12.jpg
13.jpg | 14.jpg | 15.jpg | 16.jpg

I wrote the program in a parametric way i.e. you can input any image of 2^m*2^m and ask for any number of segments n = 2^q where m and q are arbitrary numbers.

The imread opening online images is slow, you may want to have your images on disk. Also, you can uncomment the parpool to change the number of workers, if you're on a HPC cluster.