Caffe - Forward multiple images through a net in parallel - neural-network

How exactly would one do this. Right now, I have to iterate through each image and forward it. I would like to know if I can set multiple images at once and forward them through
for f in fnames:
i+=1
print i,"/",len(fnames), f
img = Image.open(f)
# scale all images to 256x256
img = img.resize((256,256), PIL.Image.ANTIALIAS)
img = numpy.array(img).astype(numpy.float32)
transformed_image = transformer.preprocess('data', img)
#print transformed_image.shape
# use CNN to predict (but don't use predicted class)
net.blobs['data'].data[...] = transformed_image
output = net.forward()

You can do this by putting all images into a single batch and then running net.forward() once for the entire batch.
bs = len(fnames) # batch size
in_shape = net.blobs['data'].data.shape
in_shape[0] = bs # set new batch size
net.blobs['data'].reshape(*in_shape)
net.reshape()
for i, f in enumerate(fnames):
img = Image.open(f)
# scale all images to 256x256
img = img.resize((256,256), PIL.Image.ANTIALIAS)
img = numpy.array(img).astype(numpy.float32)
transformed_image = transformer.preprocess('data', img)
#print transformed_image.shape
# put the image into i-th place in batch
net.blobs['data'].data[i,:,:,:] = transformed_image
# after reading all images into batch, forward once:
net.forward()

Related

How to save a single .mat file of features for many images (loop for)?

I trained two-class-classification (svmtrain) with 15 features for 18 images and I have many objects in a single image. I want to save single .mat file of features of these images. My problem is when I run this code, I have just the variables of last image.
This is my code:
NbIm = size(names1,1);
n1 = 1;
n2 = NbIm;
for n = n1:n2
%1- Read the original image
%2- Processing : Segmentation
%3- characterization :
[B3,L3,N3] = bwboundaries(ICellules); (see picture)
CC = bwconncomp(L3);
BW = bwlabel(L3);
stats1 = regionprops(CC,'Area','Centroid','Eccentricity','Perimeter','ConvexArea','ConvexHull','ConvexImage','MajorAxisLength','MinorAxisLength','Orientation','Solidity','BoundingBox');
for k = 1:length(B3),
V = []; glcm = [];
V = Im_originale(BW==k);
glcm = graycomatrix(V,'Offset',[2 0],'Symmetric', true);
stats= graycoprops(glcm);
Contrast_Cellule = stats.Contrast;
Correlation_Cellule = stats.Correlation;
Energy_Cellule = stats.Energy;
Homogeneity_Cellule = stats.Homogeneity;
Area_cellule = stats1(k).Area;
Perimeter_cellule = stats1(k).Perimeter;
Circularity_cellule = (4*pi*Area_cellule)/Perimeter_cellule^2;
Centroid_cellule = stats1(k).Centroid;
Compactness_cellule = Perimeter_cellule^2/(4*pi*Area_cellule);
MajorAxis_cellule = stats1(k). MajorAxisLength;
MinorAxis_cellule = stats1(k). MinorAxisLength;
Orientation_cellule = stats1(k).Orientation;
Eccentricity_cellule = stats1(k).Eccentricity;
Solidity_cellule = stats1(k).Solidity;
boundary3 = B3{k};
[cc] = chaincode(boundary3);
ai = cc.code;
ai = ai.';
output = calc_harmonic_coefficients(ai,30);
Ampl = 0.5*sqrt((output(1)^2)+(output(2)^2)+(output(3)^2)+(output(4)^2));
Feat(k,:) = [Area_cellule,Perimeter_cellule,Circularity_cellule,Compactness_cellule, Solidity_cellule,Eccentricity_cellule,MajorAxis_cellule,MinorAxis_cellule, Centroid_cellule,Ampl,Contrast_Cellule,Correlation_Cellule,Energy_Cellule,Homogeneity_Cellule];
end
end
save('FeatTrain.mat', 'Feat');
Every time you run the inner loop (k=...) you overwrite Feat, without ever saving it.
If you want to have a single variable for Feat, instead of saving multiple .mat files there are 2 ways to it:
If every time you run the inner loop the size of Feat is the same, you can make it a 3D matrix, by changing you line to Feat(n-n1+1,k,:)=[.... This will make a 3D matrix where each Feat(n,:,:) will be the features of each image.
If instead every time you run the inner loop Feat can change size, then use a cell array, as in Feat{n-n1+1}(k,:)=[....

How to provide input to BagOfFeatures() function in MATLAB in the form of imageSet or imageDataStore?

I want to use bagOfFeatures() function of MATLAB. But it requires input in the form of imageSet or imageDataStore. The code I want to run is given below:
Dataset = 'D:\dsktop\kinect_leap_dataset\acquisitions';
thresh1 = 0;
thresh2 = 20;
k = dir(fullfile(Dataset,'\P*\G*\*_depth.png'));
kf = {k(~[k.isdir]).folder};
kn = {k(~[k.isdir]).name};
for j=1:length(k)
% Applying thresholding to the original image
full_name = horzcat(kf{j},filesep,kn{j});
image = imread(full_name);
image_bin1 = (image < thresh2);
image_bin2 = (thresh1 < image);
image_bin = abs(image_bin2- image_bin1);
sequence{i} = image_bin;
end
% Bag of Features
bag = bagOfFeatures(sequence);
But the "sequence" is a cell class and so bagOfFeatures() is giving me errors. So I tried this:
Dataset = 'D:\dsktop\kinect_leap_dataset\acquisitions';
imgFolder = fullfile(Dataset);
imgSets = imageSet(imgFolder, 'recursive');
imgSets.Description
But now the problem is how to do the processing (thresholding) on images saved in imgSets. Also, after processing how to save all the "image_bin" images in imageSet class so that I can give them as input to the BagOfFeatures() function.
I solved this problem myself. To give input as an imageSet or imageStrore to BagOfFeatures(), we have to store all the "image_bin" images in a folder in PC.
For that, we have to create that folder in the desired location as
mkdir D:\.............\cropped
Then, we have to save the "image_bin" in that folder in a loop as
file_name = sprintf('D:/............/cropped/image_bin_%d.png',j);
imwrite(image_bin, file_name);
Then, the data from above folder is read in MATLAB memory as
imds = imageDatastore('D:/.............../cropped', 'Labels', label);
% label is an array of labels made by the user
[trainingSet, validationSet] = splitEachLabel(imds, 0.3, 'randomize');
% Bag of Features
bag = bagOfFeatures(trainingSet);
And It's done.

Error on Extract hog Features from image sets of different dimensions in Matlab. ''Subscripted assignment dimension mismatch''

How could I perform hog feature extraction from image set of different dimensions? I am getting this error on last section.
''Subscripted assignment dimension mismatch.''
%% Change Directory
cd('C:\Users\inquisitive\Documents\MATLAB\hog_test');
%% Root Folder
rootFolder = fullfile('D:\HGDatabase');
%% Load Imagesets Database Directory
imgSets = imageSet(rootFolder,'recursive');
%%
{ imgSets.Description } % display all labels on one line
[imgSets.Count] % show the corresponding count of images
%% determine the smallest amount of images in a category
minSetCount = min([imgSets.Count]);
imgSets = partition(imgSets, minSetCount, 'randomize');
[imgSets.Count]
%% partioning into training and testing sets
[trainingSet, testSet] = partition(imgSets, 0.2, 'randomize');
*%%CAN'T I SKIP THIS SECTION AND DEFINE hog_16x16 ON LOOP ITSELF WHY I NEED TO PERFORM THIS AT FIRST WITH ONE IMAGE*
img = read(trainingSet(3), 4);
[hog_16x16, vis16x16] = extractHOGFeatures(img,'CellSize',[16 16]);
cellSize = [16 16];
hogFeatureSize = length(hog_16x16);
%%Extracting Hog Features
trainingFeatures = [];
trainingLabels = [];
for hand = 1:numel(trainingSet)
numImages = trainingSet(hand).Count;
features = zeros(numImages, hogFeatureSize, 'single');
for i = 1:numImages
img = read(trainingSet(hand), i);
% Apply pre-processing steps
lvl = graythresh(img);
img = im2bw(img, lvl);
features(i, :) = extractHOGFeatures(img, 'CellSize', cellSize);
end
labels = repmat(trainingSet(hand).Description, numImages, 1);
trainingFeatures = [trainingFeatures; features];
trainingLabels = [trainingLabels; labels ];
end
Other Query:
Which image format work best .jpg or .png? I thought .png would be better? Am i right?
I took some pictures and resize them by thinking that it may train in better way? Am i thinking right or wrong? Or is there nothing to do with different size of input. What would you suggest either to perform in same size or image sets with different dimensions.
CAN'T I SKIP FOLLOWING SECTION AND DEFINE hog_16x16 ON LOOP ITSELF WHY I NEED TO PERFORM THIS AT FIRST WITH ONE IMAGE? If i can skip how to deal with that case
img = read(trainingSet(3), 4);
[hog_16x16, vis16x16] = extractHOGFeatures(img,'CellSize',[16 16]);
cellSize = [16 16];
hogFeatureSize = length(hog_16x16);
You should ensure the dimensions of the image are the same as all images, then your extracted hog_16x16 features will have the same dimensions.

MATLAB combine two avi. together

I created two avi. file and they have the same length.
I wanted to combine them on a same background and one on top another one on the bottom.
The code I used for one of the animation is below, the other one is similar.
Is there any way I can do that?
load Results.mat;
I = imread('hex08.jpg');
[rows,columns,numberOfColorChannels] = size(I);
if numberOfColorChannels >1
I = I(:,:,2);
end
background = imresize(background, [rows,columns]);
figure(1);
hold on;
for i=1:500
A=angle(i,:);
J = imrotate(I,A,'crop');
mask = J == 0;
mask = bwareafilt(mask,4);
J(mask) = background(mask);
pause(0.01)
imshow(J);
imwrite(J,[num2str(i),'.png']);
end
imageNames = dir(fullfile('*.png'));
imageNames = {imageNames.name}';
outputVideo = VideoWriter(fullfile('hex08.avi'));
outputVideo.FrameRate = 15;
open(outputVideo)
for ii = 1:length(imageNames)
img = imread(fullfile(imageNames{ii}));
writeVideo(outputVideo,img)
end
close(outputVideo)
Here is one way this can be done:
Just like you read the image into img, you can read a second image (from the second video) into img2. Then, you can create a combined image of the two: imgCombined = [img ; img2]; which will contain the first image on top and the second on bottom (This will work if both images are the same width, otherwise you will need to resize/crop). When you write to the video file, use writeVideo(outputVideo,imgCombined).

concatenate matrix to another matrix

I wrote a matlab code that reads images from folder(images are in RGB). It reads the image one by one. After reading the first image it re-sizes it and then reshapes it so that the new image dimension is (any number of rows X 3 volumes) using this function:
Vectrgb = reshape(rgb,[],3);
Then the code will read a new image.
How should I append the matrix of the second image to the one?
Below is the code:
Folder = 'fo\';
Files = dir([Folder, '\*.png']);
Y=[];
for i = 1 : length(Folder)
name = strcat('telo-phase\',Files(i).name);
image = imread(name);
rgb = imresize(image, 0.50); % resize the image
Vectrgb = reshape(rgb,[],3);
end
Vectrgb1 = Vectrgb';[ind2,ctrs2]= kmeans(double(Vectrgb1),2);
If you wat Y to be the concatanation of all RGB vectors of all images you need to add this line inside the loop
Y = cat( 1, Y, Vecrgb );
PS,
When dealing with filenames and paths it is a good practice to use fullfile command:
Files = dir( fullfile( Folder, '*.png' ) );
Makes your code platform independent.