How to find the centroids of pixel clusters within a binary image - matlab

I've written some code in MATLAB that converts an image (of stars) into a binary image using a set threshold and then labels each cluster of pixels (stars) that is above this threshold. The labelling produces an output:
e.g.
[1 1 1 0 0 0 0 0 0
1 1 0 0 0 2 2 2 0
0 0 0 3 3 0 2 0 0
0 0 0 3 3 0 0 0 0]
So each cluster of 1's, 2's, 3's etc. represents a star. I used the answer provided at this link: How to find all connected components in a binary image in Matlab? to label the pixels.
I also can't use the image processing toolbox.
The code that I have so far is shown below.
How do I now find the centroids of each pixel cluster in the image?
clc
clear all
close all
img=imread('star.jpg');
binary_image=convert2binary(img);
imshow(binary_image);
visited = false(size(binary_image));
[rows, cols] = size(binary_image);
B = zeros(rows, cols);
ID_counter = 1;
for row = 1:rows
for col = 1:cols
if binary_image(row, col) == 0
visited(row, col) = true;
elseif visited(row, col)
continue;
else
stack = [row col];
while ~isempty(stack)
loc = stack(1,:);
stack(1,:) = [];
if visited(loc(1),loc(2))
continue;
end
visited(loc(1),loc(2)) = true;
B(loc(1),loc(2)) = ID_counter;
[locs_y, locs_x] = meshgrid(loc(2)-1:loc(2)+1, loc(1)-1:loc(1)+1);
locs_y = locs_y(:);
locs_x = locs_x(:);
out_of_bounds = locs_x < 1 | locs_x > rows | locs_y < 1 | locs_y > cols;
locs_y(out_of_bounds) = [];
locs_x(out_of_bounds) = [];
is_visited = visited(sub2ind([rows cols], locs_x, locs_y));
locs_y(is_visited) = [];
locs_x(is_visited) = [];
is_1 = binary_image(sub2ind([rows cols], locs_x, locs_y));
locs_y(~is_1) = [];
locs_x(~is_1) = [];
stack = [stack; [locs_x locs_y]];
end
ID_counter = ID_counter + 1;
end
end
end
function [binary] = convert2binary(img)
[x, y, z]=size(img);
if z==3
img=rgb2gray(img);
end
img=double(img);
sum=0;
for i=1:x
for j=1:y
sum=sum+img(i, j);
end
end
threshold=100 % or sum/(x*y);
binary=zeros(x,y);
for i=1:x
for j=1:y
if img(i, j) >= threshold
binary(i, j) = 1;
else
binary(i, j)=0;
end
end
end
end

The centroid is the first order moment. It is computed by
sum(x*v)/sum(v) , sum(y*v)/sum(v)
For a binary image you can do this (I'm using a trivial loop, not vectorized code, so we can extend it later easily):
img = [1 1 1 0 0 0 0 0 0
1 1 0 0 0 2 2 2 0
0 0 0 3 3 0 2 0 0
0 0 0 3 3 0 0 0 0]; % Op's example data
bin = img==1; % A binary image
% Algorithm
sum_v = 0;
sum_iv = 0;
sum_jv = 0;
for jj=1:size(bin,2)
for ii=1:size(bin,1)
sum_v = sum_v + bin(ii,jj);
sum_iv = sum_iv + ii * bin(ii,jj);
sum_jv = sum_jv + jj * bin(ii,jj);
end
end
centroid = [sum_iv, sum_jv] / sum_v;
You could of course iterate over each of the labels of the labeled image img, and apply the above code. But that is highly inefficient. Instead, we can loop through the image once and compute all centroids at the same time. We convert sum_v etc. into vectors, containing one running sum per label:
N = max(img(:)); % number of labels
sum_v = zeros(N,1);
sum_iv = zeros(N,1);
sum_jv = zeros(N,1);
for jj=1:size(img,2)
for ii=1:size(img,1)
index = img(ii,jj);
if index>0
sum_v(index) = sum_v(index) + 1;
sum_iv(index) = sum_iv(index) + ii;
sum_jv(index) = sum_jv(index) + jj;
end
end
end
centroids = [sum_iv, sum_jv] ./ sum_v;

Related

How can i count how many function was executed in this code?

I have been studying Matlab for hobby.
This is my second question in stack-overflow.
These days I have interest in Sudoku by Matlab.
I got code from internet and I am studying this code for 3 weeks.
I want to add function which indicate how many times 'sub-function(candidates)' executed. -> how many times function works for solution.
I used to use cnt = 0 and cnt=cnt+1 for count(under if statement and while statement)
but i realize this code's structure is loop(??)
*i tried it but cnt were reset when i try, i think i know the reason of reset
but i can't write it code
Thank you for your help
function X = s2(X)
% SUDOKU Solve Sudoku using recursive backtracking.
% sudoku(X), expects a 9-by-9 array X.
% Fill in all ?singletons?.
% C is a cell array of candidate vectors for each cell.
% s is the first cell, if any, with one candidate.
% e is the first cell, if any, with no candidates.
[C,s,e] = candidates(X);
while ~isempty(s) && isempty(e)
X(s) = C{s};
[C,s,e] = candidates(X);
end
% Return for impossible puzzles.
if ~isempty(e)
return
end
% Recursive backtracking.
if any(X(:) == 0)
Y = X;
z = find(X(:) == 0,1); % The first unfilled cell.
for r = [C{z}] % Iterate over candidates.
X = Y;
X(z) = r; % Insert a tentative value.
X = s2(X); % Recursive call.
if all(X(:) > 0) % Found a solution.
return
end
end
end
% ???????????????
function [C,s,e] = candidates(X)
C = cell(9,9);
tri = #(k) 3*ceil(k/3-1) + (1:3);
for j = 1:9
for i = 1:9
if X(i,j)==0
z = 1:9;
z(nonzeros(X(i,:))) = 0;
z(nonzeros(X(:,j))) = 0;
z(nonzeros(X(tri(i),tri(j)))) = 0;
C{i,j} = nonzeros(z)';
end
end
end
L = cellfun(#length,C); % Number of candidates.
s = find(X==0 & L==1,1);
e = find(X==0 & L==0,1);
end % candidates
end % s2
i used variable X
X=[4 0 0 0 2 0 0 0 0;
0 1 0 3 0 0 5 0 0;
0 0 9 0 0 8 0 6 0;
7 0 0 6 0 0 1 0 0;
0 2 0 0 0 0 0 0 9;
0 0 3 0 0 4 0 0 0;
6 0 0 7 0 0 0 2 0;
0 8 0 0 1 0 0 0 4;
0 0 0 0 0 9 3 0 0];
You could also use a persistent variable, which should retain its value across multiple calls of the function.
For example:
function [ result ] = myfactorial( num )
% using persistent variable based on
% https://www.mathworks.com/help/matlab/ref/persistent.html
persistent numcalls;
if isempty(numcalls)
numcalls = 0;
end
numcalls = numcalls+1;
disp(strcat('numcalls is now: ', int2str(numcalls)));
% factorial function based on
% https://www.quora.com/How-can-I-create-a-factorial-function-in-MATLAB
if num > 1
result = myfactorial(num-1)*num;
else
result = 1;
end
end
Now call the function.
clear all;
result = myfactorial(5);
The output is:
numcalls is now:1
numcalls is now:2
numcalls is now:3
numcalls is now:4
numcalls is now:5

How to list all results of probability experiment in Matlab [duplicate]

I am writing a function in Matlab to model the length of stay in hospital of stroke patients. I am having difficulty in storing my output values.
Here is my function:
function [] = losdf(age, strokeType, dest)
% function to mdetermine length of stay in hospitaal of stroke patients
% t = time since admission (days);
% age = age of patient;
% strokeType = 1. Haemorhagic, 2. Cerebral Infarction, 3. TIA;
% dest = 5.Death 6.Nursing Home 7. Usual Residence;
alpha1 = 6.63570;
beta1 = -0.03652;
alpha2 = -3.06931;
beta2 = 0.07153;
theta0 = -8.66118;
theta1 = 0.08801;
mu1 = 22.10156;
mu2 = 2.48820;
mu3 = 1.56162;
mu4 = 0;
nu1 = 0;
nu2 = 0;
nu3 = 1.27849;
nu4 = 0;
rho1 = 0;
rho2 = 11.76860;
rho3 = 3.41989;
rho4 = 63.92514;
for t = 1:1:365
p = (exp(-exp(theta0 + (theta1.*age))));
if strokeType == 1
initialstatevec = [1 0 0 0 0 0 0];
elseif strokeType == 2
initialstatevec = [0 1 0 0 0 0 0];
else
initialstatevec = [0 0 (1-p) p 0 0 0];
end
lambda1 = exp(alpha1 + (beta1.*age));
lambda2 = exp(alpha2 + (beta2.*age));
Q = [ -(lambda1+mu1+nu1+rho1) lambda1 0 0 mu1 nu1 rho1;
0 -(lambda2+mu2+nu2+rho2) lambda2 0 mu2 nu2 rho2;
0 0 -(mu3+nu3+rho3) 0 mu3 nu3 rho3;
0 0 0 -(mu4+nu4+rho4) mu4 nu4 rho4;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0];
Pt = expm(t./365.*Q);
Pt = Pt(strokeType, dest);
Ft = sum(initialstatevec.*Pt);
Ft
end
end
Then to run my function I use:
losdf(75,3,7)
I want to plot my values of Ft in a graph from from 0 to 365 days. What is the best way to do this?
Do I need to store the values in an array first and if so what is the best way to do this?
Many ways to do this, one straightforward way is to save each data point to a vector while in the loop and plot that vector after you exit your loop.
...
Ft = zeros(365,1); % Preallocate Ft as a vector of 365 zeros
for t = 1:365
...
Ft(t) = sum(initialstatevec.*Pt); % At index "t", store your output
...
end
plot(1:365,Ft);

MATLAB Yalmip: unable to run optimizer; error in eliminatevariables

Bottomline:
Matlab throws the errors below and it is not obvious to me what is the root cause. The problem seems to reside in the input arguments, but I cannot figure out exactly what it is. I would greatly appreciate any help in finding it.
Index exceeds matrix dimensions.
Error in eliminatevariables (line 42)
aux(model.precalc.index2) = value(model.precalc.jj2);
Error in optimizer/subsref (line 276)
[self.model,keptvariablesIndex] =
eliminatevariables(self.model,self.model.parameterIndex,thisData(:),self.model.parameterIndex);
Error in SCMv0_justrun (line 68)
[solutions,diagnostics] = controller{inputs};
Background:
I am trying to program a Model Predictive Control but I am not very familiar yet with either Yalmip or mathematical optimization algorithms. I have made sure that the defined inputs and the actual inputs have the same dimensions, hence why I am surprised that the error has to do with matrix dimensions.
The error originates in when my code calls the optimizer.
My code is based on: https://yalmip.github.io/example/standardmpc/
Here is my code (the first part of the code is only needed to define the optimization problem and is marked between "%%%%%"; the error occurs near the end):
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yalmip('clear')
clear all
% Model data
A = eye(3);
B = [1 0 -1 0 0 0 0; 0 1 0 -1 0 0 0; 0 0 0 0 1 -1 -1];
nx = 3; % Number of states
nu = 7; % Number of inputs
% MPC data
Q = [10 10 20]';
R = [10 10 1 1 5 3 3]';
C = [50 0; 0 30];
N = 90;
ny = 2;
E = [0 0 0 0 0 1 0; 0 0 0 0 0 0 1];
u = sdpvar(repmat(nu,1,N),repmat(1,1,N));
x = sdpvar(repmat(nx,1,N+1),repmat(1,1,N+1));
r = sdpvar(repmat(ny,1,N+1),repmat(1,1,N+1));
d = sdpvar(ny,1);
pastu = sdpvar(nu,1);
dx = 0.05;
Gx=[-1*eye(3);eye(3)];
gx = [0 0 0 500 500 1000]';
COVd = [zeros(5,7);0 0 0 0 0 10 0; 0 0 0 0 0 0 10];
COVx = zeros(nx,nx);
auxa = eye(5);
auxb = zeros(5,2);
Gu = [-1*eye(7,7); auxa auxb;0 0 0 0 0 1 1];
gu = [zeros(7,1); 200; 200; 50; 50; 100; 500];
Ga = [0 0 0.5 0.5 -1 0 0];
constraints = [];
objective = 0;
for k = 1:N
r{k} = r{k} + d;
objective = objective + Q'*x{k} + R'*u{k} + (r{k}-E*u{k})'*C*(r{k}-E*u{k});
constraints = [constraints, x{k+1} == A*x{k}+B*u{k}];
COVx = A*COVx*A' + B*COVd*B';
COVGx = Gx*COVx*Gx';
StDevGx = sqrt(diag(COVGx));
chance = gx - norminv(1-dx/(length (gx)*N))*StDevGx;
constraints = [constraints, Ga*u{k}==0, Gu*u{k}<=gu, Gx*x{k}<=gx-chance];
end
objective = objective + Q'*x{N+1};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
parameters_in = {x{1},[r{:}],d,pastu};
solutions_out = {[u{:}], [x{:}]};
controller = optimizer(constraints, objective,[],parameters_in,solutions_out);
x = 100*ones(nx,1);
clf;
disturbance = randn(ny,1)*10;
oldu = zeros(nu,1);
hold on
for i = 1:150
future_r = [4*sin((i:i+N)/40);3*sin((i:i+N)/20)];% match dimensions of r
inputs = {x,future_r,disturbance,oldu};
[solutions,diagnostics] = controller{inputs};
U = solutions{1};oldu = U(1);
X = solutions{2};
if diagnostics == 1
error('The problem is infeasible');
end
x = A*x+B*u;
end
It's a bug in the latest version of YALMIP.

How to make a parity check matrix from non-systematic to systematic in Matlab? thanks

I am trying to make a parity check matrix from non-systematic to systematic. Hence, I am attaching my code below. Somewhat it is correct, but there are some problems. It would be really great if someone could help me in this.
Subject: Information theory and coding. I am working on LDPC coding and decoding. Please check the code below
MATLAB CODE:
H = [1 0 1 1 0; 0 0 1 0 1; 1 0 0 1 0; 1 0 1 1 1]
[m,n] = size(H);
k = n-m;
for i = k+1:n
%H(:,i)
ind = find(H(:,i),1,'last');
% exchanging (ind)th row and (i-k)th row
if ind < i-k
continue;
end
if ind ~= i-k
temp = H(ind,:);
H(ind,:) = H(i-k,:);
H(i-k,:) = temp;
end
I = find(H(:,i));
% Guassian elimination
for j = 1:length(I)
if I(j) ~= i-k
H(I(j),:) = mod(H(I(j),:)+H(i-k,:),2);
end
end
end
Hsys = H
For e.g.
This is my H matrix:
H =
1 0 1 1 0
0 0 1 0 1
1 0 0 1 0
1 0 1 1 1
I want to have an identity matrix inside the matrix. The dimension on H matrix here is (mxn) which is (4x5).
Generally we use Gaussian elimination method to make the Identity matrix.hence, we make operations between rows. This is how we make it systematic.
I should have matrix as this in the result:
Hsys =
0 1 0 0 0
0 0 1 0 0
1 0 0 1 0
0 0 0 0 1
I should have an identity matrix of dimension m.
Here is how I'd do it (using Gauss-Jordan elimination):
% Not your matrix since it does not have any ones in the second column.
H=[1 1 0 1 1 0 0 1 0 0;
0 1 1 0 1 1 1 0 0 0;
0 0 0 1 0 0 0 1 1 1;
1 1 0 0 0 1 1 0 1 0;
0 0 1 0 0 1 0 1 0 1];
rows = size(H, 1);
cols = size(H, 2);
r = 1;
for c = cols - rows + 1:cols
if H(r,c) == 0
% Swap needed
for r2 = r + 1:rows
if H(r2,c) ~= 0
tmp = H(r, :);
H(r, :) = H(r2, :);
H(r2, :) = tmp;
end
end
end
% Ups...
if H(r,c) == 0
error('H is singular');
end
% Forward substitute
for r2 = r + 1:rows
if H(r2, c) == 1
H(r2, :) = xor(H(r2, :), H(r, :));
end
end
% Back Substitution
for r2 = 1:r - 1
if H(r2, c) == 1
H(r2, :) = xor(H(r2, :), H(r, :));
end
end
% Next row
r = r + 1;
end

How to draw Polynomial SVM modifying this code (Matlab)

well i'm new to this website and new when it comes to Matlab and Support-Vector-Machines and the teacher gave us this code :
clear all;
clc;
X_plus = load('example2_SVM.m');
[m,n] = size(X_plus);
ligne = m;
ligne_plus = 0;
for i=1:ligne
if(X_plus(i,n)==1)
ligne_plus = ligne_plus +1;
end
end
ligne_moins = ligne-ligne_plus;
colonne = n-1;
for i=1:ligne
y(1,i) = X_plus(i,colonne+1);
end
for i=1:ligne
for j=1:ligne
s=0;
for k=1:colonne
s = s + X_plus(i,k)*X_plus(j,k);
end
H(i,j) = y(i)*y(j)*s;
end
end
f = ones(1,ligne);
A = [];
b = [];
beq = zeros(1,1);
lb = zeros(1,ligne);
ub = zeros(1,ligne);
bornes_sup = 0.5;
for i=1:ligne
ub(i) = bornes_sup;
end
Aeq = y;
f = -f;
alpha = quadprog(H,f,A,b,Aeq,beq,lb,ub);
for k=1:colonne
s=0;
for i=1:ligne
s = s + alpha(i)*y(i)*X_plus(i,k);
end
w(k) = s;
end
for i=1:ligne
if(alpha(i)>0.001)
support = i;
break;
end
end
s = 0;
for k=1:colonne
for i=1:ligne
s = s + alpha(i)*y(i)*X_plus(support,k)*X_plus(i,k);
end
end
w0 = y(support) - s;
for i=1:m
if(X_plus(i,3)==1)
plot(X_plus(i,1),X_plus(i,2),'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',5)
else
plot(X_plus(i,1),X_plus(i,2),'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','r','MarkerSize',5)
end
hold on
end
hold on
x = -10:0.1:10;
y = -10:0.1:10;
if(w(2) ~= 0)
plot(x,-w(1)/w(2)*x-w0/w(2),'--rs','LineWidth',0.2,'MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',1)
else
plot(x,-w0/w(1),'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',1)
end
and this is the example2_SVM.m :
1 0 +1
2 0 +1
1 1 +1
0 1 +1
0 2 +1
4 -1 +1
3 0 +1
3 3 -1
4 3 -1
5 3 -1
5 4 -1
5 2 -1
6 4 -1
4 2 -1
4 5 -1
so what are we doing in this code : is reading data from example2_SVM.m which contains negative and positive values to be separated using quadraprog function the result :
http://i.stack.imgur.com/Jkpsm.jpg
as you can see the points are linearly separable, my question is how to modify this code to draw a polynomial divider using this data :
1 2 +1
3 1 +1
3 2.5 +1
1 1 -1
2 3 -1
2 1 -1