Speed up deinterleave and concatenation for TIFF - performance

I work in a neuro-lab that records pictures of mouse brains. The raw files that the cameras record to record pictures from alternating cameras (picture of brain, picture of mouse head, picture of brain, etc) We're converting these files to TIFF, deinterleaving them, and then concatenating the files.
The concatenation is far too slow to be of any use. I'm not yet learned enough in Matlab to be able to troubleshoot. How can we improve the speed of this code?
%convert micam raw to tiff using image j
javaaddpath 'C:\Program Files\MATLAB\R2013a\java\mij.jar';
javaaddpath 'C:\Program Files\MATLAB\R2013a\java\ij.jar';
MIJ.start('C:\users\lee\desktop\imagej');
MIJ.run('Install...', 'install=[C:\\Users\\lee\\Desktop\\ImageJ\\macros\\Matthias\\Helmchen Macros modified djm.ijm]');
MIJ.run('Run...', 'path=[C:\\Users\\lee\\Desktop\\ImageJ\\macros\\Matthias\\Helmchen Macros modified djm.ijm]');
MIJ.run('Convert MiCam Raw to TIFF');
pause (30); %to prevent race condition, needs to be fixed to wait for input
MIJ.exit;
%prepare tiff stack folder fast
myFolder = uigetdir;
cd(myFolder);
filePattern = fullfile(myFolder, '*.tif');
tifffiles = dir(filePattern);
count = length(tifffiles);
for z = 1:count
A = tifffiles.name;
I = imreadtiffstack (A, 256);
%crop tiff stack
sizecrop = size(I);
framenum = sizecrop(3);
cropcollector = ones([100 101 256] , 'uint16'); %preallocates matrix for depositing cropped frames
for k = 1:framenum
frame = I(:,:,k);
I2 = imcrop(frame,[20 0 100 100]);
cropcollector(:,:,k)=I2;
%deinterleaves tiff stack
sizedinlv = size(cropcollector);
framenumdinlv = sizedinlv(3);
oddcollector = ones([100 101 128], 'uint16'); %preallocates array for odd deinterleaved frames
evencollector = ones([100 101 128], 'uint16'); %preallocates array for even deinterleaved frames
countodd = 0;
counteven = 0;
for k2 = (1:framenumdinlv)
if mod(k2, 2)==1
framedinlv = cropcollector(:,:,k2);
countodd = countodd +1;
oddcollector(:,:,countodd)=framedinlv;
else
framedinlv = cropcollector(:,:,k2);
counteven = counteven + 1;
evencollector(:,:,counteven)=framedinlv;
%concatenate
if mod (z, 2)==1;
oddhold = ones([100 101 128], 'uint16');
evenhold = ones([100 101 128], 'uint16');
oddhold = repmat(oddcollector, 1);
evenhold = repmat(evencollector, 1);
else
odd = num2str(1);
even = num2str(2);
brain = ones([100 101 256], 'uint16');
mouse = ones([100 101 256], 'uint16');
% nameoddframes = strcat(A(1:10), odd);
%nameevenframes = strcat(A(1:10), even);
brain = cat(3, oddhold, oddcollector);
mouse = cat(3, evenhold, evencollector);
end
end
end
end
end
%background subtraction

Related

Color image pixel permutation not reversible

I performed color image permutation using 2D sine-map for RGB image. The code uses this map to perform pixel location permutation for each RGB channel in the image. Then, I used the same map with the same initial parameters to inverse the permutation. The problem is the code only perform correct inverse permutation for one channel only the other channels is not recovered. See the attached images of the permuted and the recovered image.
%% Image Encryption Demo - Encryption and Decryption
clear all
close all
clc
%% 1. Load plaintext images
% Image 1
I = imread('D:\1\1.jpg');
Ir = I(:,:,1);
Ig = I(:,:,2);
Ib = I(:,:,3);
K=1;
%% 2. Encryption
%[CI,K] = Logistic2D_ImageCipher(I,'encryption');
[CIb,K] = Logistic2D_ImageCipher(Ib,'encryption');
clearvars -except CIb Ir Ig Ib K I;
[CIr,K] = Logistic2D_ImageCipher(Ir,'encryption');
clearvars -except CIb CIr Ir Ig Ib K I;
[CIg,K] = Logistic2D_ImageCipher(Ig,'encryption');
clearvars -except CIb CIr CIg Ir Ig Ib K I;
CI = cat(3,CIr,CIg,CIb);
%% 3. Decryption
%DI = Logistic2D_ImageCipher(CI,'decryption',K);
DIb = Logistic2D_ImageCipher(CIb,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb CI;
DIg = Logistic2D_ImageCipher(CIg,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb DIg CI;
DIr = Logistic2D_ImageCipher(CIr,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb DIg DIr CI;
DI = cat(3,DIr,DIg,DIb);
%% 4. Analaysis
% Histogram
%title('aaa');
figure,subplot(221),imshow(I,[]),subplot(222),imshow(CI,[])
subplot(223),imhist(I),subplot(224),imhist(CI)
title('aaa2');
figure,subplot(221),imshow(DI,[])
function varargout = Logistic2D_ImageCipher(P,para,K)
%% 1. Initialization
% 1.1. Genereate Random Key if K is not given
if ~exist('K','var') && strcmp(para,'encryption')
K = round(rand(1,256));
varOutN = 2;
elseif ~exist('K','var') && strcmp(para,'decryption')
error('Cannot Complete Decryption without Encryption Key')
else
varOutN = 1;
end
% 1.2. Translate K to map formats
transFrac = #(K,st,ed) sum(K(st:ed).*2.^(-(1:(ed-st+1))));
x0 = transFrac(K,1,52);
y0 = transFrac(K,53,104);
a=0.8;
b =0.3;
r = transFrac(K,105,156)*.08+1.11;
T = transFrac(K,157,208);
turb = blkproc(K(209:256),[1,8],#(x) bi2de(x));
MN = numel(P);
Logistic2D = #(x,y,a) [sin(pi*a*(y+3)*x*(1-x)), sin(pi*a*(x+3)*y*(1-y))];
format long eng
%% 2. Estimate cipher rounds
if max(P(:))>1
F = 256;
S = 4;
else
F = 2;
S = 32;
end
P = double(P);
iter = 1;
%iter = ceil(log2(numel(P))/log2(S));
%% 3. Image Cipher
C = double(P);
switch para
case 'encryption'
for i = 1:iter
tx0 = mod(log(turb(mod(i-1,6)+1)+i)*x0+T,1);
ty0 = mod(log(turb(mod(i-1,6)+1)+i)*y0+T,1);
xy = zeros(MN,2);
for n = 1:MN
if n == 1
xy(n,:) = (Logistic2D(tx0,ty0,a));
else
xy(n,:) = (Logistic2D(xy(n-1,1),xy(n-1,2),a));
end
end
R = cat(3,reshape(xy(:,1),size(P,1),size(P,2)),reshape(xy(:,2),size(P,1),size(P,2)));
C = LogisticPermutation(C,R,'encryption');
end
case 'decryption'
for i = iter:-1:1
tx0 = mod(log(turb(mod(i-1,6)+1)+i)*x0+T,1);
ty0 = mod(log(turb(mod(i-1,6)+1)+i)*y0+T,1);
xy = zeros(MN,2);
for n = 1:MN
if n == 1
xy(n,:) = (Logistic2D(tx0,ty0,a));
else
xy(n,:) = (Logistic2D(xy(n-1,1),xy(n-1,2),a));
end
end
R = cat(3,reshape(xy(:,1),size(P,1),size(P,2)),reshape(xy(:,2),size(P,1),size(P,2)));
C = LogisticPermutation(C,R,'decryption');
end
end
%% 4. Output
switch F
case 2
C = logical(C);
case 256
C = uint8(C);
end
switch varOutN
case 1
varargout{1} = C;
case 2
varargout{1} = C;
varargout{2} = K;
end
function C = LogisticPermutation(P,R,para)
C0 = zeros(size(P));
C = C0;
switch para
case 'encryption'
% 1. Shuffling within a Column
[v,Epix] = sort(R(:,:,1),1);
for i = 1:size(R,1)
C0(:,i) = P(Epix(:,i),i);
end
% 2. Shuffling within a Row
[v,Epiy] = sort(R(:,:,2),2);
for j = 1:size(R,2)
C(j,:) = C0(j,Epiy(j,:));
end
case 'decryption'
% 1. Shuffling within a Row
[v,Epiy] = sort(R(:,:,2),2);
for j = 1:size(R,2)
C0(j,Epiy(j,:)) = P(j,:);
end
% 2. Shuffling within a Column
[v,Epix] = sort(R(:,:,1),1);
for i = 1:size(R,1)
C(Epix(:,i),i) = C0(:,i);
end
end
It didn't work because you overwrote K in the encryption stage, and it was different for each channel, so the decryption only worked correctly for the last channel that created K. If you're using the MATLAB editor, you should pay attention to the mlint warnings (square at the top right that should be always be green) - you could say that this is what told me the answer to your problem.
Here's a fixed version of the first part of the script:
function q50823167
%% 1. Load plaintext images
% Image 1
I = imread(fullfile(matlabroot, 'examples', 'wavelet', 'mandrill.jpg'));
Ir = I(:,:,1);
Ig = I(:,:,2);
Ib = I(:,:,3);
%% 2. Encryption
%[CI,K] = Logistic2D_ImageCipher(I,'encryption');
[CIb,Kb] = Logistic2D_ImageCipher(Ib,'encryption');
[CIr,Kr] = Logistic2D_ImageCipher(Ir,'encryption');
[CIg,Kg] = Logistic2D_ImageCipher(Ig,'encryption');
CI = cat(3,CIr,CIg,CIb);
%% 3. Decryption
%DI = Logistic2D_ImageCipher(CI,'decryption',K);
DIb = Logistic2D_ImageCipher(CIb,'decryption',Kb);
DIg = Logistic2D_ImageCipher(CIg,'decryption',Kg);
DIr = Logistic2D_ImageCipher(CIr,'decryption',Kr);
DI = cat(3,DIr,DIg,DIb);
%% 4. Analaysis
% Histogram
%title('aaa');
figure,subplot(221),imshow(I,[]),subplot(222),imshow(CI,[])
subplot(223),imhist(I),subplot(224),imhist(CI)
title('aaa2');
figure,subplot(221),imshow(DI,[])
Note that you don't have to clear variables every time.

How to avoid overlapping between title and labels in Matlab's pie chart?

I'm using the next code to plot in a pie chart the percentage of values in a matrix that are greater/smaller than 1. The thing is that when I want to put the title above the graph, it overlaps with the label of one of the groups.
I tried replacing it with text() but it didn't worked, and Documentation on pie say nothing to this. How can I avoid this overlap?
eigen = []; % Modes array
c2 = 170; % Sound speed divided by 2
%% Room dimensions
lx = 5.74;
ly = 8.1;
lz = 4.66;
i = 1; % Index for modes array
for nz = 0:50
for ny = 0:50
for nx = 0:50
aux = c2 * sqrt((nx/lx)^2+(ny/ly)^2+(nz/lz)^2);
if aux < 400 %% If value is into our range of interest
eigen(i) = aux;
i=i+1;
end
end
end
end
eigen = round(sort(eigen'),1);
eigen
% dif = eigen(2:end)-eigen(1:end-1); % Distance between modes
x = 0; %% dif >= 1
y = 0; %% dif <= 1
dif = [];
for i=2:length(eigen)
if eigen(i)-eigen(i-1) >= 1
x = x+1;
else
y = y+1;
end
end
figure
dif = [x,y];
explode = [1 1];
graf = pie(dif,explode);
hText = findobj(graf,'Type','text');
percentValues = get(hText,'String');
txt = {'Smaller than 1 Hz: ';'Greater than 1 Hz: '};
combinedtxt = strcat(txt,percentValues);
oldExtents_cell = get(hText,'Extent');
oldExtents = cell2mat(oldExtents_cell);
hText(1).String = combinedtxt(1);
hText(2).String = combinedtxt(2);
title('Distance between modes')
You can rotate the pie chart so that the figure look better. Further, you can use position to allocate your text as follows,
figure
dif = [x,y];
explode = [1 1];
graf = pie(dif,explode);
hText = findobj(graf,'Type','text');
percentValues = get(hText,'String');
txt = {'Smaller than 1 Hz: ';'Greater than 1 Hz: '};
combinedtxt = strcat(txt,percentValues);
oldExtents_cell = get(hText,'Extent');
oldExtents = cell2mat(oldExtents_cell);
hText(1).String = combinedtxt(1);
hText(2).String = combinedtxt(2);
view([90 90]) % this is to rotate the chart
textPositions_cell = get(hText,{'Position'});
textPositions = cell2mat(textPositions_cell);
textPositions(:,1) = textPositions(:,1) + 0.2; % replace 0.2 with any offset value you want
hText(1).Position = textPositions(1,:);
hText(2).Position = textPositions(2,:);
title('Distance between modes')
You can change only the text position (without rotation) by deleting view command.

Reading AND mask of 16x16 images from ICO file in Lua

I am creating a function that will parse and ICO/CUR and convert the data into plain pixels (specific to my API) that will then be fed to a dxCreateTexture function which will create the final image. I'm currently working on the case when the images inside the ICO file are 8bpp or less. Here's how it's currently done:
I read the color palette and store each color inside an array.
I move on to reading the XOR mask which contains the indices for every pixel color and store every pixel inside another table.
I then read the AND mask which I understand is 1bpp.
The code that I will post below works perfectly for 1bpp, 4bpp and 8bpp images with a size of 32x32, XOR & AND masks being interpreted correctly, but for images with 8x8, 16x16 or 48x48 sizes (and I suspect that there are other sizes too) only the XOR mask gets interpreted correctly. Reading the AND mask will result in misplaced transparent pixels. Please keep in mind that I'm not flipping the image yet, so this code will result in an upside-down image.
local IcoSignature = string.char(0,0,1,0);
local PngSignature = string.char(137,80,78,71,13,10,26,10);
local AlphaByte = string.char(255);
local TransparentPixel = string.char(0,0,0,0);
function ParseCur(FilePath)
if (fileExists(FilePath) == true) then
local File = fileOpen(FilePath);
if (File ~= false) and (fileRead(File,4) == IcoSignature) then
local Icons = {}
for i = 1,fileReadInteger(File,2) do -- number of icons in file
local SizeX = fileReadInteger(File,1); -- icon width
if (SizeX == 0) then
SizeX = 256;
end
local SizeY = fileReadInteger(File,1); -- icon height
if (SizeY == 0) then
SizeY = 256;
end
fileRead(File,2); -- skip ColorCount and Reserved
local PlanesNumber = fileReadInteger(File,2);
local BitsPerPixel = fileReadInteger(File,2);
local Size = fileReadInteger(File); -- bytes occupied by icon
local Offset = fileReadInteger(File); -- icon data offset
Icons[i] = {
PlanesNumber = PlanesNumber,
BitsPerPixel = BitsPerPixel,
SizeX = SizeX,
SizeY = SizeY,
Texture = true
}
local PreviousPosition = fileGetPos(File);
fileSetPos(File,Offset);
if (fileRead(File,8) == PngSignature) then -- check data format (png or bmp)
fileSetPos(File,Offset);
-- to do
else
fileSetPos(File,Offset+4); -- skip BITMAPINFOHEADER Size
local SizeX = fileReadInteger(File);
local SizeY = fileReadInteger(File)/2;
local PlanesNumber = fileReadInteger(File,2);
local BitsPerPixel = fileReadInteger(File,2);
fileRead(File,24); -- skip rest of BITMAPINFOHEADER
local Pixels = {}
if (BitsPerPixel == 1) or (BitsPerPixel == 4) or (BitsPerPixel == 8) then
local Colors = {}
for j = 1,2^(PlanesNumber*BitsPerPixel) do
Colors[j] = fileRead(File,3)..AlphaByte;
fileRead(File,1);
end
local PixelsPerByte = 8/BitsPerPixel;
local CurrentByte;
for y = 1,SizeY do -- XOR mask
Pixels[y] = {}
local CurrentRow = Pixels[y];
for x = 0,SizeX-1 do
local CurrentBit = x%PixelsPerByte;
if (CurrentBit == 0) then
CurrentByte = fileReadInteger(File,1);
end
CurrentRow[x+1] = Colors[bitExtract(
CurrentByte,
(PixelsPerByte-1-CurrentBit)*BitsPerPixel,BitsPerPixel
)+1];
end
end
for y = 1,SizeY do -- AND mask
local CurrentRow = Pixels[y];
for x = 0,SizeX-1 do
local CurrentBit = x%8;
if (CurrentBit == 0) then
CurrentByte = fileReadInteger(File,1);
end
if (bitExtract(CurrentByte,7-CurrentBit,1) == 1) then
CurrentRow[x+1] = TransparentPixel;
end
end
end
for y = 1,SizeY do -- concatenate rows into strings
Pixels[y] = table.concat(Pixels[y]);
end
Icons[i].Texture = dxCreateTexture(
table.concat(Pixels)..string.char(
bitExtract(SizeX,0,8),bitExtract(SizeX,8,8),
bitExtract(SizeY,0,8),bitExtract(SizeY,8,8)
), -- plain pixels
nil,
false
);
elseif (BitsPerPixel == 16) or (BitsPerPixel == 24) or (BitsPerPixel == 32) then
-- to do
end
end
fileSetPos(File,PreviousPosition); -- continue reading next ICO header
end
fileClose(File);
return Icons;
end
end
end
I suppose that fileExists, fileOpen, fileClose, fileGetPos and fileSetPos are self-explanatory functions. The rest of the functions' arguments are as follows:
fileRead(file file, number bytes) - reads bytes bytes from file and returns them as a string
fileReadInteger(file file, [number bytes = 4], [bool order = true]) - reads an integer with the size of bytes bytes from file in order (little -edian = true, big-edian = false)
bitExtract(number value, number filed, number width)
dxCreateTexture(string pixels, [string format = "argb"], [bool mipmaps = true])
Here are some outputs of the function in its current state: http://i.imgur.com/dRlaoan.png
The first image is 16x16 with AND mask code commented out, second is 32x32 with AND mask code commented out, third is 16x16 with AND mask code and fourth is 32x32 with AND mask code. 8x8 and 48x48 images with AND mask code look the same as the third image in the demonstration.
ICO used for demonstration: http://lua-users.org/files/wiki_insecure/lua-std.ico
Thank you, #EgorSkriptunoff!
This mask is also a subject to right-padding its every line with zeroes.
This was indeed the problem. Three lines of code inside each loop solved it.
XOR mask:
if ((SizeX/PixelsPerByte)%4 ~= 0) then
fileRead(File,4-SizeX/PixelsPerByte%4);
end
AND mask:
if ((SizeX/8)%4 ~= 0) then
fileRead(File,4-SizeX/8%4);
end

Image manipulation with Matlab - intensity and tif image

I have to analyse a set of images, and these are the operations I need to perform:
sum another set of images (called open beam in the code), calculate the median and rotate it by 90 degrees;
load a set of images, listed in the file "list.txt";
the images have been collected in groups of 3. For each group, I want to produce an image whose intensity values are 3 times the image median above a certain threshold and otherwise equal to the sum of the intensity values;
for each group of three images, subtract the open beam median (calculated in 1.) from the combined image (calculated in 3.)
Considering one of the tifs produced using the process above, I have that the maximum value is 65211, which is not 3* the median for the three images of the corresponding group (I checked considering the pixel position). Do you have any suggestion on why this happens, and how I could fix it?
The code is reported below. Thanks!
%Here we calculate the average for the open beam
clear;
j = 0;
for i=1:5
s = sprintf('/Users/Alberto/Desktop/Midi/17_OB_2.75/midi_%04i.fits',i);
j = j+1;
A(j,:,:) = uint16(fitsread(s));
end
OB_median = median(A,1);
OB_median = squeeze(OB_median);
OB_median_rot=rot90(OB_median);
%Here we calculate, for each projection, the average value from the three datasets
%Read list of images from text file
fid = fopen('/Users/Alberto/Desktop/Midi/list.txt', 'r');
a = textscan(fid, '%s');
fclose(fid);
%load images
j = 0;
for i = 1:1:42 %556 entries; 543 valid values
s = sprintf('/Users/Alberto/Desktop/Midi/%s',a{1,1}{i,1});
j = j+1;
A(j,:,:) = uint16(fitsread(s));
end
threshold = 80 %This is a discretional number. I put it after noticing
%that we get the same number of pixels with a value >100 if we use 80 or 50.
k = 0;
for ii = 1:3:42
N(1,:,:) = A(ii,:,:);
N(2,:,:) = A(ii+1,:,:);
N(3,:,:) = A(ii+2,:,:);
median_N = median(N,1);
median_N = squeeze(median_N);
B(:,:) = zeros(2160,2592);
for i = 1:1:2160
for j = 1:1:2592
RMS(i,j) = sqrt((double(N(1,i,j).^2) + double(N(2,i,j).^2) + double(N(3,i,j).^2))/3);
if RMS(i,j) > threshold
%B(i,j) = 30;
B(i,j) = 3*median_N(i,j);
else
B(i,j) = A(ii,i,j) + A(ii+1,i,j) + A(ii+2,i,j);
%B(i,j) = A(ii,i,j);
end
end
end
k = k+1;
filename = sprintf('/Users/Alberto/Desktop/Midi/Edited_images/Despeckled_images/despeckled_image_%03i.tif',k);
%Now we rotate the matrix
B_rot=rot90(B);
imwrite(B_rot, filename);
%imwrite(uint16(B_rot), filename);
%Now we subtract the OB median
B_final_rot = double(B_rot) - 3*double(OB_median_rot);
filename = sprintf('/Users/Alberto/Desktop/Midi/Edited_images/Final_image/final_image_%03i.tif',k);
imwrite(uint16(B_final_rot), filename);
end
The maximum integer that can be represented by the uint16 data type is
>> a=100000; uint16(a)
ans =
65535
To circumvent this limitation you need to rescale your data as type double and adjust the range (the image contrast) to agree with the limits imposed by the uint16 data type, before saving as uint16.

Matlab SVM for Image Classification

I am using SVM function of Matlab to classify images that are read from a folder. What I want to do is first read 20 images from the folder, then use these to train the SVM, and then give a new image as input to decide whether this input image falls into the same category of these 20 training images or not. If it is, then the classification result should give me 1, if not, then I expect to receive -1.
Up to now, my written code is as follows:
imagefiles = dir('*.jpg');
nfiles = 20;
for i = 1:nfiles
currentfilename = imagefiles(i).name;
currentimage = imread(currentfilename);
images{i} = currentimage;
images{i} = im2double(images{i});
images{i} = rgb2gray(images{i});
images{i} = imresize(images{i},[200 200]);
images{i} = reshape(images{i}', 1, size(images{i},1)*size(images{i},2));
end
trainData = zeros(nfiles, 40000);
for ii=1:nfiles
trainData(ii,:) = images{ii};
end
class = [1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1];
SVMStruct = svmtrain (trainData, class);
inputImg = imread('testImg.jpg');
inputImg = im2double(inputImg);
inputImg = rgb2gray(inputImg);
inputImg = imresize(inputImg, [200 200]);
inputImg = reshape (inputImg', 1, size(inputImg,1)*size(inputImg,2));
result = svmclassify(SVMStruct, inputImg);
Since the images are read by series from the folder, so camethe cell images. Then I converted them to grayscale as shown in the code, and resized them, since those images were NOT of same size. Thus after this step, I had 20 images, all of each with size 200x200. And at last, I gave these to serve as my training dataset, with 20 rows, and 200x200 columns. I checked all of these size results, and they seemed to work fine. But right now the only problem is, no matter what kind of input image I give it to predict, it always gives me a result as 1, even for those very different images. Seems like it is not working correctly. Could someone help me check out where should be the problem here? I couldn't find any explanation from the existing sources on the internet. Thanks in advance.
Here is a function to read all images that may help you
function X = ReadImgs(Folder,ImgType)
Imgs = dir(fullfile(Folder, ImgType));
NumImgs = size(Imgs,1);
image = double(imread(fullfile(Folder, Imgs(1).name)));
X = zeros([NumImgs size(image)]);
for i=1:NumImgs,
img = double(imread(fullfile(Folder, Imgs(i).name)));
if (size(image,3) == 1)
X(i,:,:) = img;
else
X(i,:,:,:) = img;
end
end
Source: http://computervisionblog.wordpress.com/2011/04/13/matlab-read-all-images-from-a-folder-everything-starts-here/
this is should be works in MATLAB
clear all;
clc;
folder = 'gambar 1';
dirImage = dir( folder );
numData = size(dirImage,1);
M ={} ;
% read image
for i=1:numData
nama = dirImage(i).name;
if regexp(nama, '(lion|tiger)-[0-9]{1,2}.jpg')
B = cell(1,2);
if regexp(nama, 'lion-[0-9]{1,2}.jpg')
B{1,1} = double(imread([folder, '/', nama]));
B{1,2} = 1;
elseif regexp(nama, 'tiger-[0-9]{1,2}.jpg')
B{1,1} = double(imread([folder, '/', nama]));
B{1,2} = -1;
end
M = cat(1,M,B);
end
end
% convert image holder from cell to array
numDataTrain = size(M,1);
class = zeros(numDataTrain,1);
arrayImage = zeros(numDataTrain, 300 * 300);
for i=1:numDataTrain
im = M{i,1} ;
im = rgb2gray(im);
im = imresize(im, [300 300]);
im = reshape(im', 1, 300*300);
arrayImage(i,:) = im;
class(i) = M{i,2};
end
SVMStruct = svmtrain(arrayImage, class);
% test for lion
lionTest = double(imread('gambar 1/lion-test.jpg' ));
lionTest = rgb2gray(lionTest);
lionTest = imresize(lionTest, [300 300]);
lionTest = reshape(lionTest',1, 300*300);
result = svmclassify(SVMStruct, lionTest);
result
https://github.com/gunungloli666/svm-test

Resources