How to update the ( x,y ) coordinate for each frame? - matlab

I want the coordinate of x and y frame update for each frame. but the coordinate didn't do so. It only get the coordinate of the first frame.
The coding is:
EyeDetect = vision.CascadeObjectDetector('EyePairBig');
vidD = imaq.VideoDevice('winvideo',1,'MJPG_640x480');
EFrame = step(vidD);
bboxe = step(EyeDetect, EFrame);
x = bboxe(1, 1); y = bboxe(1, 2); w = bboxe(1, 3); h = bboxe(1, 4);
bboxPolygon = [x, y, x+w, y, x+w, y+h, x, y+h];
textColor = [255, 0, 0];
textLocation = [1 1];
text = ['x: ',num2str(bboxe(1)),' y: ',num2str(bboxe(2))];
textInserter = vision.TextInserter(text,'Color', textColor, 'FontSize', 12, 'Location', textLocation);
vido = step(textInserter, EFrame);
EFrame = insertShape(vido, 'Polygon', bboxPolygon);
figure; imshow(EFrame); title('Eyes Detection');
% Detect feature points in the eye region.
points = detectMinEigenFeatures(rgb2gray(EFrame), 'ROI', bboxe);
% Display the detected points.
figure, imshow(EFrame), hold on, title('Detected features');
plot(points);
pointTracker = vision.PointTracker('MaxBidirectionalError', 2);
points = points.Location; initialize(pointTracker, points, EFrame);
videoPlayer = vision.VideoPlayer('Position',... [100 100 [size(EFrame, 2), size(EFrame, 1)]+30]);
oldPoints = points;
nFrames=0;
while (nFrames<100)
% get the next frame
EFrame = step(vidD);
% Track the points. Note that some points may be lost.
[points, isFound] = step(pointTracker, EFrame);
visiblePoints = points(isFound, :);
oldInliers = oldPoints(isFound, :);
if size(visiblePoints, 1) >= 2 % need at least 2 points
[xform, oldInliers, visiblePoints] = estimateGeometricTransform(...
oldInliers, visiblePoints, 'similarity', 'MaxDistance', 4);
[bboxPolygon(1:2:end), bboxPolygon(2:2:end)] ...
= transformPointsForward(xform, bboxPolygon(1:2:end), bboxPolygon(2:2:end));
EFrame = insertShape(EFrame, 'Polygon', bboxPolygon);
% Display tracked points
%EFrame = insertMarker(EFrame, visiblePoints, '+','Color', 'white');
% Reset the points
oldPoints = visiblePoints;
setPoints(pointTracker, oldPoints);
text = ['x: ',num2str(bboxe(1)),' y: ',num2str(bboxe(2))];
textInserter = vision.TextInserter(text,'Color', textColor, 'FontSize', 12, 'Location', textLocation);
end
% Display the annotated video frame using the video player object
EFrame= step(textInserter,EFrame);
step(videoPlayer, EFrame);
nFrames= nFrames+1;
end
release(vidD); release(videoPlayer); release(pointTracker);

Replace the line
text = ['x: ',num2str(bboxe(1)),' y: ',num2str(bboxe(2))];
with this:
text = ['x: ',num2str(bboxPolygon(1)),' y: ',num2str(bboxPolygon(2))];

Related

Making colorbar tick labels a string above and below bar, remove ticks - Matlab

I am trying to reproduce the colorbar below for my chart. Specifically it is the string colorbar axis title (above and below the colorbar) that I am struggling with, the rest seems fine.
Below is my current code:
time_begin = [1981, 1, 1, 0,0,0];
time_end = [2010,12,31,23,0,0];
years = (time_begin(1):time_end(1))';
nyears = length(years);
TXx1 = randi(100, 288, 192, 30);
lat = rand(192, 1);
lon = rand(288, 1);
time = rand(30,1);
M = numel(lon);
N = numel(lat);
slope1 = zeros(M, N);
intercept1 = zeros(M, N);
T = numel(time);
x = ([ones(T, 1) years]);
for i = 1 : M
for j = 1 : N
y1 = squeeze(TXx1(i, j, :));
c = regress(y1, x);
intercept1(i, j) = c(1);
slope1(i, j) = c(2);
end
end
TXx2 = randi(100, 288, 192, 30);
slope2 = zeros(M, N);
intercept2 = zeros(M, N);
T = numel(time);
x = ([ones(T, 1) years]);
for i = 1 : M
for j = 1 : N
y2 = squeeze(TXx2(i, j, :));
c = regress(y2, x);
intercept2(i, j) = c(1);
slope2(i, j) = c(2);
end
end
figure()
set(gcf, 'color', 'w');
temp = [slope1(:) slope2(:)];
temp(temp == 0) = NaN;
[Q,Qc] = hist3(temp,'Nbins',[100 100],'CDataMode','auto');
Qx = cell2mat(Qc(1));
Qy = cell2mat(Qc(2));
Q = Q';
Q = Q./trapz(Qy,trapz(Qx,Q,2));
surf(Qx,Qy,Q,'FaceColor','interp','EdgeColor','none')
grid off
set(gca, 'Fontsize', 12, 'Fontweight', 'Bold'); %added
cmap = jet(500);
cmap(1,:) = [1,1,1];
colormap(cmap);
h=colorbar;
set(h,'position',[.91 .34 .031 .475]) %[xposition yposition width height].
set(get(h,'ylabel'),'string','Point density');
set(h,'XTickLabel',{'Low',' ',' ',' ',' ','High',});
view(0,90)
Here is my current colourbar:
Replace this line:
set(h,'XTickLabel',{'Low',' ',' ',' ',' ','High',});
with:
h.YTick = h.Limits;
h.YTickLabel = {'Low', 'High'};
This makes two tick-lines and two tick labels. By setting YTicks of the colorbar to its limits, the tick-lines get overlapped by colorbar boundary. So these get hidden and now there is no need to remove them.
However there is this TickLength property which can be used otherwise i.e.
h.TickLength = 0;
Result:

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...

Extraction of Plankton using Segmentation with Matlab

I am trying to extract plankton from a scanned image.
I segmented the plankton using the technique I found here, http://www.mathworks.com/help/images/examples/detecting-a-cell-using-image-segmentation.html
The outline is not bad, however, now I am not sure how to extract the images so each individual plankton can be saved individually. I tried to use labels but there is a lot of noise and it labels every single spec. I am wondering if there is a better way to do this.
Here is my code:
I = imread('plankton_2.jpg');
figure, imshow(I), title('original image');
[~, threshold] = edge(I, 'sobel');
fudgeFactor = .5;
BWs = edge(I,'sobel', threshold * fudgeFactor);
figure, imshow(BWs), title('binary gradient mask');
se90 = strel('line', 3, 90);
se0 = strel('line', 3, 0);
BWsdil = imdilate(BWs, [se90 se0]);
figure, imshow(BWsdil), title('dilated gradient mask');
BWdfill = imfill(BWsdil, 'holes');
figure, imshow(BWdfill);
title('binary image with filled holes');
BWnobord = imclearborder(BWdfill,1);
figure, imshow(BWnobord), title('cleared border image');
seD = strel('diamond',1);
BWfinal = imerode(BWnobord,seD);
BWfinal = imerode(BWfinal,seD);
figure, imshow(BWfinal), title('segmented image');
BWoutline = bwperim(BWfinal);
Segout = I;
Segout(BWoutline) = 0;
figure, imshow(Segout), title('outlined original image');
label = bwlabel(BWfinal);
max(max(label))
for j = 1:max(max(label))
[row, col] = find(label == j);
len = max(row) - min(row)+2;
breadth = max(col)-min(col) +2;
target = uint8(zeros([len breadth]));
sy = min(col)-1;
sx = min(row)-1;
for i = 1:size(row,1)
x = row(i,1)-sx;
y = col(i,1) - sy;
target(x,y)=I(row(i,1),col(i,1));
end
mytitle =strcat('Object Number:',num2str(j));
figure, imshow(target);mytitle;
end
for j = 1:max(max(label))
[row, col] = find(label == j);
len = max(row) - min(row)+2;
breadth = max(col)-min(col) +2;
target = uint8(zeros([len breadth]));
sy = min(col)-1;
sx = min(row)-1;
for i = 1:size(row,1)
x = row(i,1)-sx;
y = col(i,1) - sy;
target(x,y)=I(row(i,1),col(i,1));
end
mytitle =strcat('Object Number:',num2str(j));
figure, imshow(target);mytitle;
end
You should use the regionprops function to filter the detected objects by size and/or shape characteristics.

Delaunay command gives fewer of triangles than expected in MATLAB

I have got two unregistered images and a base image I use as reference for registration, image registration is performed as demonstrated in matlab example using SURF, now I have all images of 100*100 so after applying transformation matrix on both and saving all coordinates from three images in matrix named registeredPts when I apply delaunay command on a 30,000x2 matrix I get only 20,000 triangles where as as far as I know i should get 60,000 triangles approx
I have to use delaunay triangulation for image interpolation. I cannot figure out why so few number of triangles are formed though i cannot find any fault in feature based registration
close all
clear all
K = 2;
P1 = imread('C:\Users\Javeria Farooq\Desktop\project images\a.pgm');
%apply a command here that rgb2gray if it is a if it is rgb so convert it
% P1=rgb2gray(P1);
%reads the image to be registered
P2 = imread('C:\Users\Javeria Farooq\Desktop\project images\b.pgm');
% P2=rgb2gray(P2);
P3 = imread('C:\Users\Javeria Farooq\Desktop\project images\c.pgm');
% P3=rgb2gray(P3);
%reads the base image
image1_gray = makelr(P1, 1, 100, 1/2);
%image1_gray = P1;
% makes lr image of first
image2_gray= makelr(P2, 1, 100, 1/2);
image3_gray= makelr(P3, 1, 100, 1/2);
%image2_gray= P2;
%makes lr image of second
figure(1),imshow(image1_gray)
axis on;
grid on;
title('Unregistered image');
figure(2),imshow(image3_gray)
axis on;
grid on;
title('Unregistered image2');
figure(3),imshow(image2_gray)
axis on;
grid on;
title('Base image ');
impixelinfo
% both image displayed with pixel info
hold on
points_image1= detectSURFFeatures(image1_gray, 'NumScaleLevels', 100, 'NumOctaves', 12, 'MetricThreshold', 500 );
%detects surf features of first image
points_image2 = detectSURFFeatures(image2_gray, 'NumScaleLevels', 100, 'NumOctaves', 12, 'MetricThreshold', 500 );
points_image3 = detectSURFFeatures(image3_gray, 'NumScaleLevels', 100, 'NumOctaves', 12, 'MetricThreshold', 500 );
%detects surf features of second image
[features_image1, validPoints_image1] = extractFeatures(image1_gray, points_image1);
[features_image2, validPoints_image2] = extractFeatures(image2_gray, points_image2);
[features_image3, validPoints_image3] = extractFeatures(image3_gray, points_image3);
%extracts features of both images
indexPairs = matchFeatures(features_image1, features_image2, 'Prenormalized', true) ;
indexPairs1 = matchFeatures(features_image3, features_image2, 'Prenormalized', true) ;
% get matching points
matched_pts1 = validPoints_image1(indexPairs(:, 1));
matched_pts2 = validPoints_image2(indexPairs(:, 2));
matched_pts3 = validPoints_image3(indexPairs1(:, 1));
matched_pts4=validPoints_image2(indexPairs1(:, 2));
figure(4); showMatchedFeatures(image1_gray,image2_gray,matched_pts1,matched_pts2,'montage');
legend('matched points 1','matched points 2');
figure(5); showMatchedFeatures(image3_gray,image2_gray,matched_pts3,matched_pts4,'montage');
%matched features of both images are displayed
legend('matched points 3','matched points 2');
% Compute the transformation matrix using RANSAC
[tform, inlierFramePoints, inlierPanoPoints, status] = estimateGeometricTransform(matched_pts1, matched_pts2, 'projective');
[tform1, inlierFramePoints, inlierPanoPoints, status] = estimateGeometricTransform(matched_pts3, matched_pts4, 'projective');
%figure(6); showMatchedFeatures(image1_gray,image2_gray,inlierPanoPoints,inlierFramePoints,'montage');
%tform = estimateGeometricTransform(matched_pts1,matched_pts2,'projective')
%calculate transformation matrix using projective transform
T=tform.T;
r=[];
A=[];
l=1
[N1 N2]=size(image2_gray)
registeredPts = zeros(N1*N2,2);
pixelVals = zeros(N1*N2,1);
for row = 1:N1
for col = 1:N2
pixNum = (row-1)*N2 + col;
pixelVals(pixNum,1) = image2_gray(row,col);
registeredPts(pixNum,:) = [col,row];
end
end
[r]=transformPointsForward(tform,registeredPts(:,:));
[q]=transformPointsForward(tform1,registeredPts(:,:));
%coordinates of base image
image2_gray=double(image2_gray);
R=2;
r1=r(:,1);
r2=r(:,2);
for row = 1:N1
for col = 1:N2
pixNum = N1*N2 + (row-1)*N2 + col;
pixelVals(pixNum,1) = image1_gray(row,col);
registeredPts(pixNum,:) = [r1(col,:),r2(col,:)];
end
end
q1=q(:,1);
q2=q(:,2);
for row = 1:N1
for col = 1:N2
pixNum = N1*N2 +N1*N2+ (row-1)*N2 + col;
pixelVals(pixNum,1) = image3_gray(row,col);
registeredPts(pixNum,:) = [q1(col,:),q2(col,:)];
end
end
tri = delaunayTriangulation();
tri.Points=[registeredPts(:,1),registeredPts(:,2)];
i figured out the problem in code
for row = 1:N1
for col = 1:N2
pixNum = N1*N2 + (row-1)*N2 + col;
pixelVals(pixNum,1) = image1_gray(row,col);
registeredPts(pixNum,:) = [r1(col,:),r2(col,:)];
end
end
here same registered points are reassigned again and again, i corrected it by assigning the points out of for loop using
registeredPts=[registeredPts;r]
now i m getting above 60,000 triangles which works fine

How to plot an equilateral color triangle?

I would like to make a color plot in MATLAB similar to this plot:
I have managed to create all the points [x,y] needed in order to create the vertexes and I have a map with colors of each vertex, so I can get the following.
But I do not get it how to make the axis work.
Code so far:
% Equilateral grid
tcorner = [0.0, 0.5, 1.0;
0.0, 1.0*sqrt(3)/2, 0.0];
tg = triangle_grid( 1/0.05, tcorner );
tgx = tg(1,:);
tgy = tg(2,:);
% Create triangles
tri = delaunay(tgx,tgy);
% Plot
h = trisurf(tri, tgx, tgy, colorvector);
And the grid function:
function triangle_grid(n, tcorner)
ng = ( ( n + 1 ) * ( n + 2 ) ) / 2;
tg = zeros ( 2, ng );
p = 0;
for i = 0 : n
for j = 0 : n - i
k = n - i - j;
p = p + 1;
tg(1:2,p) = ( i * t(1:2,1) + j * t(1:2,2) + k * t(1:2,3) ) / n;
end
end
end
The main problem is that you can't rotate the axes to the right position, because the always flip to the lower side. So, you need to create them.
Here is how:
% Equilateral grid
tcorner = [0.0, 0.5, 1.0; % x
0.0, 1.0*sqrt(3)/2, 0.0]; % y
tg = triangle_grid( 1/0.05, tcorner);
tgx = tg(1,:);
tgy = tg(2,:);
% Create triangles
tri = delaunay(tgx,tgy);
col = rand(size(tgx));
trisurf(tri,tgx,tgy,col)
view(0,90)
colormap('lines')
% setting the axes:
ax = gca;
grid off
ax.YAxis.Visible = 'off';
ticks = (0:20:80).';
% bottom axis:
tickpos = linspace(tcorner(1,1),tcorner(1,3),numel(ticks)+1);
ax.XAxis.FontSize = 14;
ax.XAxis.TickValues = tickpos(1:end-1);
ax.XAxis.TickLabels = ticks;
ax.XAxis.TickLabelRotation = 45;
xlabel('X axis title');
% left & right axis:
ticksxpos = linspace(tcorner(1,1),tcorner(1,3),numel(ticks)*2+1);
ticksypos = linspace(tcorner(2,1),tcorner(2,2),numel(ticks)+1);
text(ticksxpos(numel(ticks)+1:-1:2)-0.03,... % left
ticksypos(end:-1:2)+0.03,...
num2str(ticks),'FontSize',14,...
'VerticalAlignment','bottom',...
'HorizontalAlignment','left',...
'Rotation',-45)
text(ticksxpos(end:-1:numel(ticks)+2)+0.05,... % right
ticksypos(1:end-1)-0.03,...
num2str(ticks),'FontSize',14,...
'VerticalAlignment','bottom',...
'HorizontalAlignment','right')
ax.Parent.Color = 'w';
% titles:
text(tcorner(1,2)/2-0.06,tcorner(2,2)/2+0.06,...
'Left title','FontSize',14,...
'HorizontalAlignment','center',...
'Rotation',45)
text(tcorner(1,2)+tcorner(1,2)/2+0.06,tcorner(2,2)/2+0.06,...
'Right title','FontSize',14,...
'HorizontalAlignment','center',...
'Rotation',-45)
and we get...