Matlab. How to implement tracking with counter on top of boxes? - matlab

Hello I have tried using the example in
https://www.mathworks.com/help/vision/examples/tracking-pedestrians-from-a-moving-car.html and now I want to add a counter to replace the score. I have tried mixing the example in https://www.mathworks.com/help/vision/examples/motion-based-multiple-object-tracking.html. I have tried using the method it use to add in counter above the box. but to no avil.
Below are the codes.
function PedestrianTrackingFromMovingCameraExample()
videoFile = 'vippedtracking.mp4';
scaleDataFile = 'pedScaleTable.mat'; % An auxiliary file that helps to determine the size of a pedestrian at different pixel locations.
video = VideoReader(videoFile);
obj = setupSystemObjects(videoFile, scaleDataFile);
detector = peopleDetectorACF('caltech');
tracks = initializeTracks();
nextId = 1;
option.scThresh = 0.3;
option.gatingThresh = 0.9;
option.gatingCost = 100;
option.costOfNonAssignment = 10;
option.timeWindowSize = 16;
option.confidenceThresh = 2;
option.ageThresh = 8;
option.visThresh = 0.6;
while hasFrame(video)
frame = readFrame();
[centroids, bboxes, scores] = detectPeople();
predictNewLocationsOfTracks();
[assignments, unassignedTracks, unassignedDetections] = ...
detectionToTrackAssignment();
updateAssignedTracks();
updateUnassignedTracks();
deleteLostTracks();
createNewTracks();
displayTrackingResults();
if ~isOpen(obj.videoPlayer)
break;
end
end
function obj = setupSystemObjects(videoFile,scaleDataFile)
obj.reader = vision.VideoFileReader(videoFile, 'VideoOutputDataType', 'uint8');
obj.videoPlayer = vision.VideoPlayer('Position', [29, 597, 643, 386]);
ld = load(scaleDataFile, 'pedScaleTable');
obj.pedScaleTable = ld.pedScaleTable;
end
function tracks = initializeTracks()
tracks = struct(...
'id', {}, ...
'color', {}, ...
'bboxes', {}, ...
'scores', {}, ...
'kalmanFilter', {}, ...
'age', {}, ...
'totalVisibleCount', {}, ...
'confidence', {}, ...
'predPosition', {}, ...
'consecutiveInvisibleCount', {});
end
function frame = readFrame()
frame = step(obj.reader);
end
function [centroids, bboxes, scores] = detectPeople()
resizeRatio = 1.5;
frame = imresize(frame, resizeRatio, 'Antialiasing',false);
[bboxes, scores] = detect(detector, frame, ...
'WindowStride', 2,...
'NumScaleLevels', 4, ...
'SelectStrongest', false);
height = bboxes(:, 4) / resizeRatio;
y = (bboxes(:,2)-1) / resizeRatio + 1;
yfoot = min(length(obj.pedScaleTable), round(y + height));
estHeight = obj.pedScaleTable(yfoot);
invalid = abs(estHeight-height)>estHeight*option.scThresh;
bboxes(invalid, :) = [];
scores(invalid, :) = [];
[bboxes, scores] = selectStrongestBbox(bboxes, scores, ...
'RatioType', 'Min', 'OverlapThreshold', 0.6);
if isempty(bboxes)
centroids = [];
else
centroids = [(bboxes(:, 1) + bboxes(:, 3) / 2), ...
(bboxes(:, 2) + bboxes(:, 4) / 2)];
end
end
function predictNewLocationsOfTracks()
for i = 1:length(tracks)
bbox = tracks(i).bboxes(end, :);
predictedCentroid = predict(tracks(i).kalmanFilter);
tracks(i).predPosition = [predictedCentroid - bbox(3:4)/2, bbox(3:4)];
end
end
function [assignments, unassignedTracks, unassignedDetections] = ...
detectionToTrackAssignment()
predBboxes = reshape([tracks(:).predPosition], 4, [])';
cost = 1 - bboxOverlapRatio(predBboxes, bboxes);
cost(cost > option.gatingThresh) = 1 + option.gatingCost;
[assignments, unassignedTracks, unassignedDetections] = ...
assignDetectionsToTracks(cost, option.costOfNonAssignment);
end
function updateAssignedTracks()
numAssignedTracks = size(assignments, 1);
for i = 1:numAssignedTracks
trackIdx = assignments(i, 1);
detectionIdx = assignments(i, 2);
centroid = centroids(detectionIdx, :);
bbox = bboxes(detectionIdx, :);
correct(tracks(trackIdx).kalmanFilter, centroid);
T = min(size(tracks(trackIdx).bboxes,1), 4);
w = mean([tracks(trackIdx).bboxes(end-T+1:end, 3); bbox(3)]);
h = mean([tracks(trackIdx).bboxes(end-T+1:end, 4); bbox(4)]);
tracks(trackIdx).bboxes(end+1, :) = [centroid - [w, h]/2, w, h];
tracks(trackIdx).age = tracks(trackIdx).age + 1;
tracks(trackIdx).scores = [tracks(trackIdx).scores; scores(detectionIdx)];
tracks(trackIdx).totalVisibleCount = ...
tracks(trackIdx).totalVisibleCount + 1;
tracks(trackIdx).consecutiveInvisibleCount = 0;
T = min(option.timeWindowSize, length(tracks(trackIdx).scores));
score = tracks(trackIdx).scores(end-T+1:end);
tracks(trackIdx).confidence = [max(score), mean(score)];
end
end
function updateUnassignedTracks()
for i = 1:length(unassignedTracks)
idx = unassignedTracks(i);
tracks(idx).age = tracks(idx).age + 1;
tracks(idx).bboxes = [tracks(idx).bboxes; tracks(idx).predPosition];
tracks(idx).scores = [tracks(idx).scores; 0];
tracks(idx).consecutiveInvisibleCount = ...
tracks(idx).consecutiveInvisibleCount + 1;
T = min(option.timeWindowSize, length(tracks(idx).scores));
score = tracks(idx).scores(end-T+1:end);
tracks(idx).confidence = [max(score), mean(score)];
end
end
function deleteLostTracks()
if isempty(tracks)
return;
end
ages = [tracks(:).age]';
totalVisibleCounts = [tracks(:).totalVisibleCount]';
visibility = totalVisibleCounts ./ ages;
confidence = reshape([tracks(:).confidence], 2, [])';
maxConfidence = confidence(:, 1);
lostInds = (ages <= option.ageThresh & visibility <= option.visThresh) | ...
(maxConfidence <= option.confidenceThresh);
tracks = tracks(~lostInds);
end
function createNewTracks()
unassignedCentroids = centroids(unassignedDetections, :);
unassignedBboxes = bboxes(unassignedDetections, :);
unassignedScores = scores(unassignedDetections);
for i = 1:size(unassignedBboxes, 1)
centroid = unassignedCentroids(i,:);
bbox = unassignedBboxes(i, :);
score = unassignedScores(i);
kalmanFilter = configureKalmanFilter('ConstantVelocity', ...
centroid, [2, 1], [5, 5], 100);
newTrack = struct(...
'id', nextId, ...
'color', 255*rand(1,3), ...
'bboxes', bbox, ...
'scores', score, ...
'kalmanFilter', kalmanFilter, ...
'age', 1, ...
'totalVisibleCount', 1, ...
'confidence', [score, score], ...
'predPosition', bbox, ...
'consecutiveInvisibleCount', 0);
tracks(end + 1) = newTrack; %#ok<AGROW>
nextId = nextId + 1;
end
end
function displayTrackingResults()
displayRatio = 4/3;
frame = imresize(frame, displayRatio);
minVisibleCount = 8;
if ~isempty(tracks)
reliableTrackInds = ...
[tracks(:).totalVisibleCount] > minVisibleCount;
reliableTracks = tracks(reliableTrackInds);
ids = int32([reliableTracks(:).id]);
labels = cellstr(int2str(ids'));
predictedTrackInds = ...
[reliableTracks(:).consecutiveInvisibleCount] > 0;
isPredicted = cell(size(labels));
isPredicted(predictedTrackInds) = {'predicted'};
labels = strcat(labels, isPredicted);
ages = [tracks(:).age]';
confidence = reshape([tracks(:).confidence], 2, [])';
maxConfidence = confidence(:, 1);
avgConfidence = confidence(:, 2);
opacity = min(0.5,max(0.1,avgConfidence/3));
noDispInds = (ages < option.ageThresh & maxConfidence < option.confidenceThresh) | ...
(ages < option.ageThresh / 2);
for i = 1:length(tracks)
if ~noDispInds(i)
bb = tracks(i).bboxes(end, :);
bb(:,1:2) = (bb(:,1:2)-1)*displayRatio + 1;
bb(:,3:4) = bb(:,3:4) * displayRatio;
frame = insertObjectAnnotation(frame, ...
'rectangle', bb, ...
labels, ...
'Color', tracks(i).color);
end
end
end
step(obj.videoPlayer, frame);
end
end

Related

I need help plotting different permutations of an if/else command in different colors on the same plot

Basically I have a code where it produces a plot of all possible permutations between Cost and Reliability. There's a total of 864 data points split up between 8 rows. Five of the rows have 2 options and three of them 3 options.
Given here is a copy of my code. I'm trying to have the permutations of 'Other Cameras' and 'Depth & Structure Testing' have a different color with the other six possibilities. I tried using the 'gscatter' command but didn't have much luck with it.
I believe I need to have the scatter command in the if/else statements themselves, although I'm not too sure what to plot in the 'X' and 'Y' for the 'scatter' command. Currently my code is set up for plotting all the data in one color. I deleted my code with the 'gscatter' because I got many errors and when I tried to fix them the plot ultimately didn't work as planned.
% Pareto_Eval
baseline_cost = 45;
nrows = 8;
%Initialize Variables
for aa = 1:nrows
cost_delta(aa) = 0;
reliability(aa) = 1;
end
icount = 1;
%Propulsion
for row1 = 1:2
if row1 == 1
cost_delta(1)= -7;
reliability(1) = 0.995;
elseif row1==2
cost_delta(1)=0;
reliability(1)=.99;
end
%Entry Mode
for row2 = 1:2
if row2 == 1
cost_delta(2) = -3;
reliability(2) = .99;
else
cost_delta(2) = 0;
reliability(2) = .98;
end
%Landing Method
for row3 = 1:3
if row3 == 1 %if needs declaration
cost_delta(3)= 0;
reliability(3) = .99;
elseif row3 == 2 %elseif needs declaration
cost_delta(3) = 4;
reliability(3) = .995;
else %else does not need declaration
cost_delta(3) = -2;
reliability(3) = .95;
end
%Lander Type
for row4 = 1:3
if row4 == 1
cost_delta(4)= 10;
reliability(4) = .99;
elseif row4 == 2
cost_delta(4) = 0;
reliability(4) = .99;
else
cost_delta(4) = 15;
reliability(4) = .95;
end
%Rover Type
for row5 = 1:2
if row5 == 1
cost_delta(5)= -2;
reliability(5) = .98;
else
cost_delta(5) = 0;
reliability(5) = .975;
end
%Power Source
for row6 = 1:2
if row6 == 1
cost_delta(6) = -3;
reliability(6) = .95;
else
cost_delta(6) = 0;
reliability(6) = .995;
end
%Depth & Structure Testing
for row7 = 1:2
if row7 == 1
cost_delta(7) = 0;
reliability(7) = .99;
else
cost_delta(7) = 2;
reliability(7) = .85;
end
%Other Cameras
for row8 = 1:3
if row8 == 1
cost_delta(8)= -1;
reliability(8) = .99;
elseif row8 == 2
cost_delta(8) = -1;
reliability(8) = .99;
else
cost_delta(8) = 0;
reliability(8) = .9801;
end
cost_delta_total = 0;
reliability_product = 1;
for bb=1:nrows
cost_delta_total = cost_delta_total + cost_delta(bb);
reliability_product = reliability_product*reliability(bb);
end
total_cost(icount) = baseline_cost + cost_delta_total;
total_reliability(icount) = reliability_product;
icount = icount + 1;
end; end; end; %Rows 1,2,3
end; end; end; %Rows 4,5,6
end; end; %Rows 7,8
%Plot the Pareto Evaluation
fignum=1;
figure(fignum)
sz = 5;
scatter(total_reliability, total_cost, sz, 'blue')
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
Any help is appreciated. I don't have a lot of experience with Matlab and I've tried looking around for help but nothing really worked.
Here is a sample code to make questions easier I created:
% Pareto_Eval
baseline_cost = 55;
nrows = 3;
%Initialize Variables
for aa = 1:nrows
cost_delta(aa) = 0;
reliability(aa) = 1;
end
icount = 1;
%Group 1
for row1 = 1:2
if row1 == 1
cost_delta(1)= 5;
reliability(1) = 0.999;
elseif row1==2
cost_delta(1) = 0;
reliability(1) = .995;
end
%Group 2
for row2 = 1:2
if row2 == 1
cost_delta(2) = 0;
reliability(2) = .98;
else
cost_delta(2) = -2;
reliability(2) = .95;
end
%Group 3
for row3 = 1:2
if row3 == 1
cost_delta(3) = 3;
reliability(3) = .997;
else
cost_delta(3) = 0;
reliability(3) = .96;
end
%initializing each row
cost_delta_total = 0;
reliability_product = 1;
for bb = 1:nrows
cost_delta_total = cost_delta_total + cost_delta(bb);
reliability_product = reliability_product*reliability(bb);
end
total_cost(icount) = baseline_cost + cost_delta_total;
total_reliability(icount) = reliability_product;
icount = icount + 1;
end
end
end
fignum=1;
figure(fignum)
sz = 25;
scatter(total_reliability, total_cost, sz)
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
Basically I need to make a plot in each if-loop, but I'm not sure how to do it and have them all on the same plot
sounds like an interesting project! Not sure if I understood your intended plots correctly, but hopefully the code below gets you a bit closer to what you are looking for.
I've started off with a rather deep mess of nested for loops (as you did) but kept it more concise bybuilding a permutations matrix.
counter = 0;
for propulsion_options = 1:2
for entry_mode = 1:2
for landing_method = 1:3
for lander_type = 1:3
for rover_type = 1:2
for power_source = 1:2
for depth_testing = 1:2
for other_cameras = 1:3
counter = counter +1
permutations(counter,:) = [...
propulsion_options,...
entry_mode,...
landing_method,...
lander_type,...
rover_type,...
power_source,...
depth_testing,...
other_cameras];
end
end
end
end
end
end
end
end
This way I kept the actual scoring out of the loops, and perhaps easier to tweak the values. I initialised the cost and reliabiltiy arrays to be the same size as the permutations array:
cost_delta = zeros(size(permutations));
reliability = zeros(size(permutations));
Then for each metric, I searched the permutations array for all occurances of each possible value and assigned the appropriate score:
%propulsion
propertyNo = 1;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -7;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.995;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
%entry_mode (2)
propertyNo = 2;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -3;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.98;
%landing_method (3)
propertyNo = 3;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 4;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = -2;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.995;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.95;
%lander_type (3)
propertyNo = 4;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 10;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = 15;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.95;
%rover_type (2)
propertyNo = 5;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -2;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.98;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.975;
%power_source (2)
propertyNo = 6;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -3;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.95;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.995;
%depth_testing (2)
propertyNo = 7;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 2;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.85;
%other_cameras (3)
propertyNo = 8;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -1;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = -1;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.9801;
Then each permutation can have a total cost / reliabiltiy score by summing and takign the product along the second dimension:
cost_delta_total = sum(cost_delta,2);
reliability_product = prod(reliability,2);
Finally, you can plot all points (as per your original):
%Plot the Pareto Evaluation
fignum=1;
figure(fignum)
sz = 5;
scatter(reliability_product, cost_delta_total, sz, 'b')
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
or you can create an index into the permutations by searching for specific property values and plot these different colours (actually this bit answers your most specific question of how to plot two things on the same axes - you just need the hold on; command):
propertyNo = 7;
indexDepth1 = find(permutations(:,propertyNo)==1);
indexDepth2 = find(permutations(:,propertyNo)==2);
fignum=2;
figure(fignum)
sz = 5;
scatter(reliability_product(indexDepth1), cost_delta_total(indexDepth1), sz, 'k');
hold on;
scatter(reliability_product(indexDepth2), cost_delta_total(indexDepth2), sz, 'b');
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
legend('Depth & Structure Test 1','Depth & Structure Test 2')
propertyNo = 8;
indexCam1 = find(permutations(:,propertyNo)==1);
indexCam2 = find(permutations(:,propertyNo)==2);
indexCam3 = find(permutations(:,propertyNo)==3);
fignum=3;
figure(fignum)
sz = 5;
scatter(reliability_product(indexCam1), cost_delta_total(indexCam1), sz, 'k');
hold on;
scatter(reliability_product(indexCam2), cost_delta_total(indexCam2), sz, 'b');
scatter(reliability_product(indexCam3), cost_delta_total(indexCam3), sz, 'g');
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
legend('Other Camera 1','Other Camera 2','Other Camera 3')
Good luck with the mission! When is launch day?

Matlab - polygon and line intersection

Based on Matlab - Draw angles lines over circle and get the intersecting points
I tried the following code that should find the intersecting points and mark them. Unfortunately, it does not work. Do you have an idea how I can solve it?
Script:
clc;
clear;
close all;
r=1000;
nCircle = 1000;
t = linspace(0,2*pi,nCircle);
xCircle = 0+ r*sin(t);
yCircle = 0+ r*cos(t);
pgon = polyshape(xCircle,yCircle );
line(xCircle,yCircle );
axis equal;
hold on;
nAngles = 45;
lineLength = r+50;
for angle = 0:nAngles:359
xLine(1) = 0;
yLine(1) = 0;
xLine(2) = xLine(1) + lineLength * cosd(angle);
yLine(2) = yLine(1) + lineLength * sind(angle);
plot(xLine, yLine);
lineseg = [xLine; yLine];
intersectCoord = intersect(pgon,lineseg);
scatter(intersectCoord(2,2),intersectCoord(1,2));
end
The update script only check the last generated line but it still does not work with intersect:
clc;
clear;
close all;
r=1000;
nCircle = 1000;
t = linspace(0,2*pi,nCircle);
xCircle = 0+ r*sin(t);
yCircle = 0+ r*cos(t);
objectCircle = rot90([xCircle; yCircle]);
line(xCircle,yCircle);
axis equal;
hold on;
nAngles = 35;
lineLength = r+5;
for angle = 0:nAngles:360
disp(angle);
xLine(1) = 0;
yLine(1) = 0;
xLine(2) = xLine(1) + lineLength * cosd(angle);
yLine(2) = yLine(1) + lineLength * sind(angle);
plot(xLine, yLine);
lineseg = [xLine; yLine];
end
coefficients = polyfit([xLine(1), xLine(2)], [ yLine(1), yLine(2)], 1);
a = coefficients (1);
b = coefficients (2);
for xLineCoord = 0:lineLength
i=xLineCoord+1;
yLineCoord=a*xLineCoord +b ;
yLineCoordArray(i, :) = yLineCoord;
xLineCoordArray(i, :) = i;
end
objectLine = [xLineCoordArray, yLineCoordArray];
C = intersect(objectLine,objectCircle);

Matlab: imcrop throws error while C code generation

in matlab while compiling to c code imcrop failed to run.
is there is any alternative method or any way to suppress?
I am using Matlab2016a. Below is code snippet:
if ~isempty(bbox);
bbox = bbox(1,1:4);
Ic = imcrop(im,bbox);
bboxeye = step(faceDetectorLeye, Ic);
end
Edit:
fullcode
function signal = detectFatigue(im)
% Create a detector object
faceDetector = vision.CascadeObjectDetector('ClassificationModel','FrontalFaceLBP','MinSize',[100 100]);
faceDetectorLeye = vision.CascadeObjectDetector('EyePairBig');
% Detect faces
bbox = step(faceDetector, im);
if ~isempty(bbox);
bbox = bbox(1,1:4);
Ic = imcrop(im,bbox);
bboxeye = step(faceDetectorLeye, Ic);
if ~isempty(bboxeye);
bboxeye = bboxeye(1,1:4);
Eeye = imcrop(Ic,bboxeye);
[~, nce, ~ ] = size(Eeye);
% Divide into two parts
Leye = Eeye(:,1:round(nce/2),:);
Reye = Eeye(:,round(nce/2+1):end,:);
% make grascale
Leye = rgb2gray(Leye);
Reye = rgb2gray(Reye);
Leye = filterim(Leye);
Reye = filterim(Reye);
lroi = [ 12 5 30 16 ];
rroi = [ 18 5 30 16 ];
Leyeroi = imcrop(Leye,lroi);
Reyeroi = imcrop(Reye,rroi);
[lc, ~ ] = findcircle(Leyeroi);
[rc, ~ ] = findcircle(Reyeroi);
if isempty(lc) && isempty(rc)
signal = 1;
else
signal = 0;
end
end
end
function Leye=filterim(Leye)
se = strel('disk',2,4);
% dilate graysacle
Leye = imdilate(Leye,se);
% erode grayscale
Leye = imerode(Leye,se);
Leye = imadjust(Leye);
Leye = imcomplement(Leye);
Leye = im2bw(Leye,0.95);
Leye = imresize(Leye,[30 60]);
function [c, r] = findcircle(Leyeroi)
[c ,r ] = imfindcircles(Leyeroi,[5 9],'ObjectPolarity','bright','Sensitivity',0.95);
[rm,id] = max(r);
r = rm;
c = c(id,:);
if ~isempty(c)
c(1) = c(1) + 15;
c(2) = c(2) + 7;
end
and to test the detectFatigue.m below is the function
function testdetectFatigue()
vid=webcam(1);
for loop=1:10
im=snapshot(vid);
detectFatigue(im);
end

Occasionally, figure size is not set properly in Matlab

I tried to set same figure size for several images using for loop in matlab and save in png
But some (usually one) of them has different size.
In below code, I tried to save image in (48,64).
Why some figure sizes are not set properly as I commanded?
nMarker = 5;
mark = ['o', 's', 'd', '^', 'p'];
nSize = 3;
mSize = [9, 18, 27];
nRow = 48;
nCol = 64;
BG = zeros(nRow, nCol);
idxStage = 2;
numAction = 1;
numPositionX = 4;
numPositionY = 4;
xtrain = [1,2,3,4];
ytrain = [1,2,3,4];
xpos = [20, 30, 40, 50];
ypos = [8, 18, 28, 38];
nStepS = 10;
nStepB = 10;
nStep = nStepS + nStepB;
for a = 1
for x = 1:numPositionX
for y = 1:numPositionY
for obj = 1:nMarker
for s = 1:nSize
obj_command = x*1000 + y*100 + obj*10 + s;
fig1 = figure(1);
imagesc(BG)
hold on
scatter(xpos(x), ypos(y), mSize(s), mark(obj), 'k', 'filled')
axis off
set(fig1, 'Position', [500, 500, 64, 48]);
set(gca,'position',[0 0 1 1],'units','normalized')
F = getframe(gcf);
pause(0.05)
[X, Map] = frame2im(F);%
tmp_frame = rgb2gray(X);
tmp_im_fn = sprintf('tmp/image_seq%04d.png',obj_command);
imwrite(tmp_frame, tmp_im_fn)
clf
end
end
end
end
end
I found some trick to solve the problem for now.
I put,
fig1 = figure(1);
drawnow
in front of the for loop and it seems all sizes are equal now.
But still waiting for better solution...

In my code error is Index Exceeds Matrix Dimension

my code gives an error and that is Index exceeds matrix dimensions.It runs perfectly for nsample=10 but when I use nsamples=other value it gives error.
The error starts from line 108 that means when dataright(1:20) =
output(1:20);but it runs when I used dataright(1:10) = output(1:10).
function icall(block)
setup(block);
function setup(block)
block.NumInputPorts = 0;
block.NumOutputPorts = 4;
block.OutputPort(1).SamplingMode = 'sample';
%% Setup functional port to default
block.SetPreCompPortInfoToDefaults;
%% Setup output port
block.SampleTimes = [0 1];
block.SimStateCompliance = 'DefaultSimState';
block.RegBlockMethod('Start', #Start);
block.RegBlockMethod('Outputs', #Outputs); % Required
block.RegBlockMethod('Update', #Update);
block.RegBlockMethod('Terminate', #Terminate); % Required
block.RegBlockMethod('SetInputPortSamplingMode', #SetInpPortFrameData);
block.RegBlockMethod('PostPropagationSetup', #DoPostPropSetup);
function DoPostPropSetup(block)
% Setup Dwork
block.NumDworks = 4;
block.Dwork(1).Name = 'Nothing';
block.Dwork(1).Dimensions = 1;
block.Dwork(1).DatatypeID = 0;
block.Dwork(1).Complexity = 'Real';
block.Dwork(1).UsedAsDiscState = false;
block.Dwork(2).Name = 'Nothing1';
block.Dwork(2).Dimensions = 1;
block.Dwork(2).DatatypeID = 0;
block.Dwork(2).Complexity = 'Real';
block.Dwork(2).UsedAsDiscState = false;
block.Dwork(3).Name = 'Nothing2';
block.Dwork(3).Dimensions = 1;
block.Dwork(3).DatatypeID = 0;
block.Dwork(3).Complexity = 'Real';
block.Dwork(3).UsedAsDiscState = false;
block.Dwork(4).Name = 'Nothing3';
block.Dwork(4).Dimensions = 1;
block.Dwork(4).DatatypeID = 0;
block.Dwork(4).Complexity = 'Real';
block.Dwork(4).UsedAsDiscState = false;
%endfunction
%endfunction
function Start(block)
fullpathToDll = 'Z:\Farha\2015_02_26_photometer_Datenlogger\PC-Software\CGMultChan.dll';
fullpathToHeader = 'Z:\Farha\2015_02_26_photometer_Datenlogger\PC-Software\CGMultChan.h';
fullpathToHeader;
fullpathToDll;
loadlibrary(fullpathToDll, fullpathToHeader);
libfunctions ('CGMultChan');
delete(instrfindall);
serialPort = 'COM1';
IP = calllib('CGMultChan', 'CGMultChan_Connect', '192.168.100.158'); %Connect to Data Loger
if (IP == 0)
end
out = instrfind('Port', 'COM1');
%Open Serial COM Port
s = serial(serialPort);
set(s, 'BaudRate', 57600, 'DataBits', 8, 'Parity', 'none', 'StopBits', 1, 'FlowControl', 'none', 'Terminator', 'CR');
set(s, 'Timeout', 20);
fopen(s);
TI_ms = calllib('CGMultChan', 'CGMultChan_SetIntTime', .02 * 100);
tic
block.Dwork(1).Data = 1;
block.Dwork(2).Data = 2;
block.Dwork(3).Data = 3;
block.Dwork(4).Data = 5;
function Outputs(block)
block.OutputPort(1).Data = block.Dwork(1).Data; %+ %block.InputPort(1).Data;
block.OutputPort(2).Data = block.Dwork(2).Data;
block.OutputPort(3).Data = block.Dwork(3).Data;
block.OutputPort(4).Data = block.Dwork(4).Data;
count = 0;
function Update(block)
nsamples = 20
count = 0
while (count < nsamples)
BufferSize = 16;
pBuffer = libpointer('singlePtr', zeros(BufferSize, 1));
data2 = calllib('CGMultChan', 'CGMultChan_MeasureAll', pBuffer); %Measurement
output = pBuffer.Value
count = count + 1;
time(count) = toc; %Extract Elapsed Time
dataright(count) = output(1)
dataup(count) = output(2)
databack(count) = output(3)
datafront(count) = output(5)
end
dataright(1:20) = output(1:20);
dataup(1:20) = output(1:20);
databack(1:20) = output(1:20);
datafront(1:20) = output(1:20);
block.Dwork(1).Data = double(dataright(1));
block.Dwork(2).Data = double(dataup(2));
block.Dwork(3).Data = double(databack(3));
block.Dwork(4).Data = double(datafront(5));
%end Update
function SetInpPortFrameData(block, idx, fd)
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = fd;
end
%%
function Terminate(block)
serialPort = 'COM1';
s = serial(serialPort);
fclose(s);
clear pBuffer;
calllib('CGMultChan', 'CGMultChan_Disconnect'); %Disconnect from Data Logger
This is a Level 2 S function code which generates simulink block. It connects a data logger with computer. That means its an object oriented code. I solved the problem changing the buffer size pbuffer=500. So that matrix size of data output is increased.