matlab function to return an image - matlab

I have created a function in matlab which returns an image:
function [BW3] =lineAnalysis( BW1, O)
BW2 = double(BW1 > 0);
BW3 = BW2(2:end, :); % <-- REMOVE 1st LINE (ARTIFACT)!
if O==0; % 1 for left
BW3 = fliplr(BW3); % <-- FLIP IT HERE!
end
BW3_orig = BW3; % <-- SAVE ORIGINAL VERSION
% STEP 1
n = 10; t = 0.9;
c = 0:(n - 1);
j0 = 1;
while mean(mean(BW3(1 + c, j0 + c))) < t
j0 = j0 + 1;
end
% STEP 2
i0 = 1;
while mean(mean(BW3(i0 + c, 1 + c))) < t
i0 = i0 + 1;
end
% STEP 3
a = (1 - j0) / (i0 - 1);
b = j0 - a;
for i = 1:i0
for j = 1:round(a * i + b)
BW3(i, j) = 0;
end
end
% STEP 4
w = 20;
for i = 1:round(i0 - w / a)
for j = max(1, round(a * i + b + 1)):round(a * i + b + w)
BW3(i, j) = 1;
end
end
% PLOT RESULT
[BW3] = size(BW3);
[nr, nc] = size(BW3);
% figure
subplot(122), imagesc(BW3), colormap(gray)
axis equal off, axis([1, nc, 1, nr]), title('Corrected')
This works perfectly.
However I would like to return the result in my main program instead of executing the line
imshow(BW3);
within the function.
I have tried doing this:
[BW3]=lineAnalysis(P, O);
I then tried to show the image by doing
imshow(BW3);
However this doesnt work when I show the image like this. It simply diplays one black image and one white image.
Can anyone tell me how to fix this??
Thanks :)

The problem is near the end of your code:
function [BW3] =lineAnalysis( BW1, O)
%% your calculations here
% PLOT RESULT
[BW3] = size(BW3);
imshow(BW3);
In the line [BW3] = size(BW3); you are replacing the image with a 2 element vector that has the numbers of rows and columns of your image.

Related

Berlekamp Massey Algorithm for BCH simplified binary version

I am trying to follow Lin, Costello's explanation of the simplified BM algorithm for the binary case in page 210 of chapter 6 with no success on finding the error locator polynomial.
I'm trying to implement it in MATLAB like this:
function [locator_polynom] = compute_error_locator(syndrome, t, m, field, alpha_powers)
%
% Initial conditions for the BM algorithm
polynom_length = 2*t;
syndrome = [syndrome; zeros(3, 1)];
% Delta matrix storing the powers of alpha in the corresponding place
delta_rho = uint32(zeros(polynom_length, 1)); delta_rho(1)=1;
delta_next = uint32(zeros(polynom_length, 1));
% Premilimnary values
n_max = uint32(2^m - 1);
% Initialize step mu = 1
delta_next(1) = 1; delta_next(2) = syndrome(1); % 1 + S1*X
% The discrepancy is stored in polynomial representation as uint32 numbers
value = gf_mul_elements(delta_next(2), syndrome(2), field, alpha_powers, n_max);
discrepancy_next = bitxor(syndrome(3), value);
% The degree of the locator polynomial
locator_degree_rho = 0;
locator_degree_next = 1;
% Update all values
locator_polynom = delta_next;
delta_current = delta_next;
discrepancy_rho = syndrome(1);
discrepancy_current = discrepancy_next;
locator_degree_current = locator_degree_next;
rho = 0; % The row with the maximum value of 2mu - l starts at 1
for i = 1:t % Only the even steps are needed (so make t out of 2*t)
if discrepancy_current ~= 0
% Compute the correction factor
correction_factor = uint32(zeros(polynom_length, 1));
x_exponent = 2*(i - rho);
if (discrepancy_current == 1 || discrepancy_rho == 1)
d_mu_times_rho = discrepancy_current * discrepancy_rho;
else
alpha_discrepancy_mu = alpha_powers(discrepancy_current);
alpha_discrepancy_rho = alpha_powers(discrepancy_rho);
alpha_inver_discrepancy_rho = n_max - alpha_discrepancy_rho;
% The alpha power for dmu * drho^-1 is
alpha_d_mu_times_rho = alpha_discrepancy_mu + alpha_inver_discrepancy_rho;
% Equivalent to aux mod(2^m - 1)
alpha_d_mu_times_rho = alpha_d_mu_times_rho - ...
n_max * uint32(alpha_d_mu_times_rho > n_max);
d_mu_times_rho = field(alpha_d_mu_times_rho);
end
correction_factor(x_exponent+1) = d_mu_times_rho;
correction_factor = gf_mul_polynoms(correction_factor,...
delta_rho,...
field, alpha_powers, n_max);
% Finally we add the correction factor to get the new delta
delta_next = bitxor(delta_current, correction_factor(1:polynom_length));
% Update used data
l = polynom_length;
while delta_next(l) == 0 && l>0
l = l - 1;
end
locator_degree_next = l-1;
% Update previous maximum if the degree is higher than recorded
if (2*i - locator_degree_current) > (2*rho - locator_degree_rho)
locator_degree_rho = locator_degree_current;
delta_rho = delta_current;
discrepancy_rho = discrepancy_current;
rho = i;
end
else
% If the discrepancy is 0, the locator polynomial for this step
% is passed to the next one. It satifies all newtons' equations
% until now.
delta_next = delta_current;
end
% Compute the discrepancy for the next step
syndrome_start_index = 2 * i + 3;
discrepancy_next = syndrome(syndrome_start_index); % First value
for k = 1:locator_degree_next
value = gf_mul_elements(delta_next(k + 1), ...
syndrome(syndrome_start_index - k), ...
field, alpha_powers, n_max);
discrepancy_next = bitxor(discrepancy_next, value);
end
% Update all values
locator_polynom = delta_next;
delta_current = delta_next;
discrepancy_current = discrepancy_next;
locator_degree_current = locator_degree_next;
end
end
I'm trying to see what's wrong but I can't. It works for the examples in the book, but not always. As an aside, to compute the discrepancy S_2mu+3 is needed, but when I have only 24 syndrome coefficients how is it computed on step 11 where 2*11 + 3 is 25?
Thanks in advance!
It turns out the code is ok. I made a different implementation from Error Correction and Coding. Mathematical Methods and gives the same result. My problem is at the Chien Search.
Code for the interested:
function [c] = compute_error_locator_v2(syndrome, m, field, alpha_powers)
%
% Initial conditions for the BM algorithm
% Premilimnary values
N = length(syndrome);
n_max = uint32(2^m - 1);
polynom_length = N/2 + 1;
L = 0; % The curent length of the LFSR
% The current connection polynomial
c = uint32(zeros(polynom_length, 1)); c(1) = 1;
% The connection polynomial before last length change
p = uint32(zeros(polynom_length, 1)); p(1) = 1;
l = 1; % l is k - m, the amount of shift in update
dm = 1; % The previous discrepancy
for k = 1:2:N % For k = 1 to N in steps of 2
% ========= Compute discrepancy ==========
d = syndrome(k);
for i = 1:L
aux = gf_mul_elements(c(i+1), syndrome(k-i), field, alpha_powers, n_max);
d = bitxor(d, aux);
end
if d == 0 % No change in polynomial
l = l + 1;
else
% ======== Update c ========
t = c;
% Compute the correction factor
correction_factor = uint32(zeros(polynom_length, 1));
% This is d * dm^-1
dd_sum = modulo(alpha_powers(d) + n_max - alpha_powers(dm), n_max);
for i = 0:polynom_length - 1
if p(i+1) ~= 0
% Here we compute d*d^-1*p(x_i)
ddp_sum = modulo(dd_sum + alpha_powers(p(i+1)), n_max);
if ddp_sum == 0
correction_factor(i + l + 1) = 1;
else
correction_factor(i + l + 1) = field(ddp_sum);
end
end
end
% Finally we add the correction factor to get the new locator
c = bitxor(c, correction_factor);
if (2*L >= k) % No length change in update
l = l + 1;
else
p = t;
L = k - L;
dm = d;
l = 1;
end
end
l = l + 1;
end
end
The code comes from this implementation of the Massey algorithm

How to implement B-Spline in matrix form?

I am simply trying to draw a cubic B-Spline using the matrix representation given in this paper: http://vision.ucsd.edu/~kbranson/research/bsplines/bsplines.pdf
Specifically, I am trying the to exactly replicate the formula in section 3 (using placement matrix G) of the PDF. But I am not sure where I am going wrong. It keeps producing straight lines. Can anyone point me out what is wrong with the following code (it should run on any version of matlab; its quite simple) ?
% main.m
clc; clear;
n_cpts = 5;
deg = 3;
cpts = randi(30, n_cpts, 2);
n_knots = n_cpts + deg + 1;
knots = 0:(n_knots-1);
ts = knots(deg):0.05:knots(end-deg);
curve = [];
for t = ts(1:end-1)
k = floor(t);
T = [1, t, t^2, t^3];
B = Bi(k);
G = Gi(k, n_cpts);
p = T * B * G * cpts;
curve = [curve; p];
end
scatter(curve(:,1), curve(:,2));
The helper functions
% Bi.m
% The 'B' matrix
function [B] = Bi(i)
B = [[ -(1./6.)*i^3, (1./6.)*(3*i^3 + 3*i^2 - 3*i + 1), -(1./2.)*(i^3)-(i^2)+2./3., (1./2.)*(i+1)^3 ];
[ +(1./2.)*i^2, -(1./2.)*(3*i-1)*(i+1), (1./2.)*(3*i^2 + 4*i), -(1./2.)*(i+1)^2 ];
[ (1./2.)*i, (1./2.)*(3*i+1), -(1./2.)*(3*i+2), (1./2.)*(i+1) ];
[ (1./6.), -(1./2.), (1./2.), -(1./6.) ]];
end
% Gi.m
% The 'G' matrix
function [G] = Gi(i, L)
G = zeros(4, L);
for m = 1:4
for n = 1:L
if n == i+m-3
G(m,n) = 1;
end
end
end
end
My output looks like this:

solving integral in rectangular method in matlab

This is my code to make an integration in the rectangular method in the matlab
f=#(x) (x^(1/2))
a = 1
b = 10
% step size
h = 0.25
n = 0 % the counter
xn= a + (n * h)
%%
%Rectangle Method:
s=0
for i =0:n-1
s = s + f(xn)
end
Rectangle = h * s
the answer should be around 20, but i'm getting 29.5
what's the problem?
Two errors:
1) xn is not updated.
2) number of points n is set to zero.
There are other minor issues which I did not fix, e.g. right and left boundary points should both contribute to the sum with weight 1/2.
Quick fix:
f=#(x) (x^(1/2));
a = 1;
b = 10 ;
% step size
h = 0.25;
n = (b-a)/h; % the counter
%%
%Rectangle Method:
s=0;
for i =0:n-1
xn= a + (i * h);
s = s + f(xn);
end
Rectangle = h * s;

Error in evaluating a function

EDIT: The code that I have pasted is too long. Basicaly I dont know how to work with the second code, If I know how calculate alpha from the second code I think my problem will be solved. I have tried a lot of input arguments for the second code but it does not work!
I have written following code to solve a convex optimization problem using Gradient descend method:
function [optimumX,optimumF,counter,gNorm,dx] = grad_descent()
x0 = [3 3]';%'//
terminationThreshold = 1e-6;
maxIterations = 100;
dxMin = 1e-6;
gNorm = inf; x = x0; counter = 0; dx = inf;
% ************************************
f = #(x1,x2) 4.*x1.^2 + 2.*x1.*x2 +8.*x2.^2 + 10.*x1 + x2;
%alpha = 0.01;
% ************************************
figure(1); clf; ezcontour(f,[-5 5 -5 5]); axis equal; hold on
f2 = #(x) f(x(1),x(2));
% gradient descent algorithm:
while and(gNorm >= terminationThreshold, and(counter <= maxIterations, dx >= dxMin))
g = grad(x);
gNorm = norm(g);
alpha = linesearch_strongwolfe(f,-g, x0, 1);
xNew = x - alpha * g;
% check step
if ~isfinite(xNew)
display(['Number of iterations: ' num2str(counter)])
error('x is inf or NaN')
end
% **************************************
plot([x(1) xNew(1)],[x(2) xNew(2)],'ko-')
refresh
% **************************************
counter = counter + 1;
dx = norm(xNew-x);
x = xNew;
end
optimumX = x;
optimumF = f2(optimumX);
counter = counter - 1;
% define the gradient of the objective
function g = grad(x)
g = [(8*x(1) + 2*x(2) +10)
(2*x(1) + 16*x(2) + 1)];
end
end
As you can see, I have commented out the alpha = 0.01; part. I want to calculate alpha via an other code. Here is the code (This code is not mine)
function alphas = linesearch_strongwolfe(f,d,x0,alpham)
alpha0 = 0;
alphap = alpha0;
c1 = 1e-4;
c2 = 0.5;
alphax = alpham*rand(1);
[fx0,gx0] = feval(f,x0,d);
fxp = fx0;
gxp = gx0;
i=1;
while (1 ~= 2)
xx = x0 + alphax*d;
[fxx,gxx] = feval(f,xx,d);
if (fxx > fx0 + c1*alphax*gx0) | ((i > 1) & (fxx >= fxp)),
alphas = zoom(f,x0,d,alphap,alphax);
return;
end
if abs(gxx) <= -c2*gx0,
alphas = alphax;
return;
end
if gxx >= 0,
alphas = zoom(f,x0,d,alphax,alphap);
return;
end
alphap = alphax;
fxp = fxx;
gxp = gxx;
alphax = alphax + (alpham-alphax)*rand(1);
i = i+1;
end
function alphas = zoom(f,x0,d,alphal,alphah)
c1 = 1e-4;
c2 = 0.5;
[fx0,gx0] = feval(f,x0,d);
while (1~=2),
alphax = 1/2*(alphal+alphah);
xx = x0 + alphax*d;
[fxx,gxx] = feval(f,xx,d);
xl = x0 + alphal*d;
fxl = feval(f,xl,d);
if ((fxx > fx0 + c1*alphax*gx0) | (fxx >= fxl)),
alphah = alphax;
else
if abs(gxx) <= -c2*gx0,
alphas = alphax;
return;
end
if gxx*(alphah-alphal) >= 0,
alphah = alphal;
end
alphal = alphax;
end
end
But I get this error:
Error in linesearch_strongwolfe (line 11) [fx0,gx0] = feval(f,x0,d);
As you can see I have written the f function and its gradient manually.
linesearch_strongwolfe(f,d,x0,alpham) takes a function f, Gradient of f, a vector x0 and a constant alpham. is there anything wrong with my declaration of f? This code works just fine if I put back alpha = 0.01;
As I see it:
x0 = [3; 3]; %2-element column vector
g = grad(x0); %2-element column vector
f = #(x1,x2) 4.*x1.^2 + 2.*x1.*x2 +8.*x2.^2 + 10.*x1 + x2;
linesearch_strongwolfe(f,-g, x0, 1); %passing variables
inside the function:
[fx0,gx0] = feval(f,x0,-g); %variable names substituted with input vars
This will in effect call
[fx0,gx0] = f(x0,-g);
but f(x0,-g) is a single 2-element column vector with these inputs. Assingning the output to two variables will not work.
You either have to define f as a proper named function (just like grad) to output 2 variables (one for each component), or edit the code of linesearch_strongwolfe to return a single variable, then slice that into 2 separate variables yourself afterwards.
If you experience a very rare kind of laziness and don't want to define a named function, you can still use an anonymous function at the cost of duplicating code for the two components (at least I couldn't come up with a cleaner solution):
f = #(x1,x2) deal(4.*x1(1)^2 + 2.*x1(1)*x2(1) +8.*x2(1)^2 + 10.*x1(1) + x2(1),...
4.*x1(2)^2 + 2.*x1(2)*x2(2) +8.*x2(2)^2 + 10.*x1(2) + x2(2));
[fx0,gx0] = f(x0,-g); %now works fine
as long as you always have 2 output variables. Note that this is more like a proof of concept, since this is ugly, inefficient, and very susceptible to typos.

Save animated warp as a GIF file in MATLAB

I could finally manage to get ripple effect. I animated it and want to save the animation to a GIF file.
But I get a fixed image in the gif file.
The animation works great in MATLAB but I don't know why it won't get saved.
im = imread('peppers.png');
[m,n,~] = size(im);
n = linspace(-4 * pi,4 * pi,n);
m = linspace(-4 * pi,4 * pi,m);
[X,Y] = meshgrid(m,n);
d = (X .^ 2 + Y .^ 2) .^ .5;
d = d / max(d(:));
d = (d - .5) * 2 * pi;
j = 1;
figure(1);
for i = 0 : .2 : 2 * pi
Z = cos(2 * d + i) .* exp(-.01 .* d);
h = warp(X,Y,Z,im);
axis equal; axis off;
f = getframe;
[I,~] = frame2im(f);
[I,cm] = rgb2ind(I,256);
if j == 1
imwrite(I,cm,'B.gif','gif', 'Loopcount',inf);
else
imwrite(I,'B.gif','gif','WriteMode','append','DelayTime',1/24);
end
j = 0;
end
Question 1 How can I save it (or what is the problem with current code)?
Question 2 How can I save it in a way that there is no white background ?
(for example with view([0 45]) and a little zoom)
Thanks,
Edit Thanks to #Ayb4btu, I made some improvements,
However using close all slows thing down, even sometimes getframe captures my desktop!
For some reason the imwrite doesn't like how the figure is being updated. The following inelegant code works by closing the figure and drawing a new one:
clear all, close all, clc
I = imread('peppers.png');
[m,n] = size(I);
n = linspace(-4 * pi,4 * pi,n);
m = linspace(-4 * pi,4 * pi,m);
[X,Y] = meshgrid(m,n);
d = (X .^ 2 + Y .^ 2) .^ .5;
d = d / max(d(:));
d = (d - .5) * 2 * pi;
j = 1;
for p = 0 : .2 : 4 * pi
figure(1)
Z = cos(2 * d + p) .* exp(-.01 .* d);
h = warp(X,Y,Z,I);
axis equal; axis off;
frame = getframe(1);
im = frame2im(frame);
[A,map] = rgb2ind(im,256);
if j == 1
imwrite(A,map,'B.gif','gif', 'Loopcount',Inf,'DelayTime',1/24);
else
imwrite(A,map,'B.gif','gif','WriteMode','append','DelayTime',1/24);
end
j = 0;
close all
end
Use this as a basis and you might be able to figure out where the problem lies.
As for your question 2, this code uses the background color of the figure, though I believe imwrite has a color property that you can play with.