Does anyone know how to use the Hough transform to detect the strongest lines in the binary image:
A = zeros(7,7);
A([6 10 18 24 36 38 41]) = 1;
Using the (rho; theta) format with theta in steps of 45° from -45° to 90°. And how do I show the accumulator array in MATLAB as well.
Any help or hints please?
Thank you!
If you have access to the Image Processing Toolbox, you can use the functions HOUGH, HOUGHPEAKS, and HOUGHLINES:
%# your binary image
BW = false(7,7);
BW([6 10 18 24 36 38 41]) = true;
%# hough transform, detect peaks, then get lines segments
[H T R] = hough(BW);
P = houghpeaks(H, 4);
lines = houghlines(BW, T, R, P, 'MinLength',2);
%# show accumulator matrix and peaks
imshow(H./max(H(:)), [], 'XData',T, 'YData',R), hold on
plot(T(P(:,2)), R(P(:,1)), 'gs', 'LineWidth',2);
xlabel('\theta'), ylabel('\rho')
axis on, axis normal
colormap(hot), colorbar
%# overlay detected lines over image
figure, imshow(BW), hold on
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
plot(xy(:,1), xy(:,2), 'g.-', 'LineWidth',2);
end
hold off
Each pixel (x,y) maps to a set of lines (rho,theta) that run through it.
Build an accumulator matrix indexed by (rho theta).
For each point (x,y) that is on, generate all the quantized (rho, theta) values that correspond to (x,y) and increment the corresponding point in the accumulator.
Finding the strongest lines corresponds to finding peaks in the accumulator.
In practice, the descritization of the polar parameters is important to get right. Too fine and not enough points will overlap. Too coarse and each bin could correspond to multiple lines.
in pseudo code with liberties:
accum = zeros(360,100);
[y,x] = find(binaryImage);
y = y - size(binaryImage,1)/2; % use locations offset from the center of the image
x = x - size(binaryImage,2)/2;
npts = length(x);
for i = 1:npts
for theta = 1:360 % all possible orientations
rho = %% use trigonometry to find minimum distance between origin and theta oriented line passing through x,y here
q_rho = %% quantize rho so that it fits neatly into the accumulator %%
accum(theta,rho) = accum(theta,rho) + 1;
end
end
Related
I want to plot circles in Hadamard matrix pattern of order 8,16, and 32. So far, I have a code for plotting 2D arrays of circles.
%Plotting an N by N arrays of circles
clc; clear;
n_circles = 8; % Define the number of circles to be plotted
R = 40; % Define the radius of the basic circle
Len=1024;
M=zeros(Len); % Create the hole mask
% Get the indices of the points inside the basic circle
M0 = zeros(2*R+1); % Initialize the basic mask
I = 1:(2*R+1); % Define the x and y coordinates of the basic mask
x = (I - R)-1;
y = (R - I)+1;
[X,Y] = meshgrid(x,y); % Create the mask
A = (X.^2 + Y.^2 <= R^2);
[xx,yy]=ind2sub(size(M0),find(A == true));
%plot
for ii=1:n_circles
for jj=1:n_circles
MidX=Len/2+(ii-n_circles/2-0.5)*(2*R);
MidY=Len/2+(jj-n_circles/2-0.5)*(2*R);
% [MidX MidY]
M(sub2ind(size(M),MidX+xx-R-1,MidY+yy-R-1))=1;
end
end
figure(1)
imshow(M)
I searched on how to plot a Hadamard matrix, and from the Mathworks documentation, the hadamard matrix function
H = hadamard(n)
returns the Hadamard matrix of order n. How do I incorporate this in my original code so that the final result will generate an image of circles plotted in a Hadamard pattern, where the value of 1 indicates a circle while -1 is null (absence of circle)?
Thanks,
add in th begining
H = hadamard(n_circles);
and inside the loops change to:
M(sub2ind(size(M),MidX+xx-R-1,MidY+yy-R-1))=H(ii,jj);
I'm trying to find vanishing points of vanishing lines to estimate a depth map for a 2D image.
First, I detected the vanishing lines of the 2D image using hough transform. Here is my code in Matlab:
Img =imread('landscape.bmp'); %read the 2D image
%Convert the image to Grayscale
I=rgb2gray(Img);
%Edge Detection
Ie=edge(I,'sobel');
%Hough Transform
[H,theta,rho] = hough(Ie);
% Finding the Hough peaks (number of peaks is set to 5)
P = houghpeaks(H,5,'threshold',ceil(0.2*max(H(:))));
x = theta(P(:,2));
y = rho(P(:,1));
%Vanishing lines
lines = houghlines(I,theta,rho,P,'FillGap',170,'MinLength',350);
[rows, columns] = size(Ie);
figure, imshow(~Ie)
hold on
xy_1 = zeros([2,2]);
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
% Get the equation of the line
x1 = xy(1,1);
y1 = xy(1,2);
x2 = xy(2,1);
y2 = xy(2,2);
slope = (y2-y1)/(x2-x1);
xLeft = 1; % x is on the left edge
yLeft = slope * (xLeft - x1) + y1;
xRight = columns; % x is on the reight edge.
yRight = slope * (xRight - x1) + y1;
plot([xLeft, xRight], [yLeft, yRight], 'LineWidth',1,'Color','blue');
%intersection of two lines (the current line and the previous one)
slopee = #(line) (line(2,2) - line(1,2))/(line(2,1) - line(1,1));
m1 = slopee(xy_1);
m2 = slopee(xy);
intercept = #(line,m) line(1,2) - m*line(1,1);
b1 = intercept(xy_1,m1);
b2 = intercept(xy,m2);
xintersect = (b2-b1)/(m1-m2);
yintersect = m1*xintersect + b1;
plot(xintersect,yintersect,'m*','markersize',8, 'Color', 'red')
xy_1 = xy;
% Plot original points on the lines .
plot(xy(1,1),xy(1,2),'x','markersize',8,'Color','yellow');
plot(xy(2,1),xy(2,2),'x','markersize',8,'Color','green');
end
Now I need to find the vanishing point to be able to estimate the depth map.
The vanishing point is chosen as the intersection point with the greatest number of intersections around it.
My question, in other words, is how can I find the intersection of a number of lines (vanishing lines) in Matlab? I guess one way to do it is to find the point whose sum of squared distances from all lines is minimal, but not sure how to do that in Matlab?
Any help would be appreciated.
Edit: I tried to find the intersection of the lines, but I could only find the intersection of each a line and the line after it. I don't know how to find the intersection of all the lines?
Here is an example of a picture I am using:
https://www.dropbox.com/s/mbdt6v60ug1nymb/landscape.bmp?dl=0
I am posting a link because I don't have enough reputations to post an image.
A simplistic approach:
You should be able to create an array with all the intersection points between the lines.
Pseudo code:
for i = 1:length(lines)-1
for j = i+1:length(lines)
//add intersection of lines i and j
If you have all the intersections, you could simply take the average.
OR, take the approach written up here:
https://math.stackexchange.com/questions/61719/finding-the-intersection-point-of-many-lines-in-3d-point-closest-to-all-lines
3d can be simplified to 2d :)
So I have already implemented every part of a Hough Transform on my own, except for actually plotting the lines back onto the original image.
I can set up my array of data that I have like this.
points | theta | rho
-------|-------|----
[246,0] -90 -246
[128,0] -90 -128
[9,0] -90 -9
[0,9] 0 9
[0,128] 0 128
[0,246] 0 246
The points are the points that were converted from the peaks in Polar Coordinates. So now I need to draw all six of these lines and I have had no luck.
Edit
So I tried to change my code based off suggestions. This is what I came up with.
function help(img, outfile, peaks, rho, theta)
imshow(img);
x0 = 1;
xend = size(img,2);
peaks_len=length(peaks);
for i=1:peaks_len
peak=peaks(i,:);
r_ind=peak(1);
t_ind=peak(2);
r=rho(r_ind);
th=theta(t_ind);
%display([r,th,peak]);
%// if a vertical line, then draw a vertical line centered at x = r
% display([r, th]);
if (th == 0)
display('th=0');
display([1, size(img,1)]);
line([r r], [1 size(img,1)], 'Color', 'green');
else
%// Compute starting y coordinate
y0 = abs((-cosd(th)/sind(th))*x0 + (r / sind(th)))+11;%-25;
%// Compute ending y coordinate
yend = abs((-cosd(th)/sind(th))*xend + (r / sind(th)))+11;%-25;
display('y');
display([y0, yend]);
display('x');
display([x0 xend]);
%// Draw the line
line([x0 xend], [y0 yend], 'Color', 'green');
end
end
end
I had to change from r==0 to th==0 because th=0 would give NAN errors when r was not 0.
Based off the peaks, I then used that to get the data I needed to then calculate some values... but for some reason this isn't plotting well.
If you notice the + 11 for both y values. I had to do that to get the lines to be where they need to. I have a feeling something else went wrong.
I did change it so that my Rho values are all now positive.
If you recall from the parameterization of the Hough space, the direct relation between rho,theta to x,y is:
rho = x*cos(theta) + y*sin(theta)
Bear in mind that x,y represent the column and row location respectively. In addition, the origin is defined at the top-left corner of the image. Now that you want to plot the equation of the line, you have your rho and theta. Simply re-arrange the equation so that you can solve for an equation of the line of the form y = mx + b:
As such , simply loop over each rho and theta you have and draw a line that starts from the origin at x = 0 up to the limit of your image x = width-1. However, because MATLAB is 1-indexed, we need to go from x = 1 to x = width. Supposing that your rho and theta are stored in separate arrays of the same lengths and you have your edge image stored in im, you can do something like this:
imshow(im); %// Show the image
hold on; %// Hold so we can draw lines
numLines = numel(rho); %// or numel(theta);
%// These are constant and never change
x0 = 1;
xend = size(im,2); %// Get the width of the image
%// For each rho,theta pair...
for idx = 1 : numLines
r = rho(idx); th = theta(idx); %// Get rho and theta
%// Compute starting y coordinate
y0 = (-cosd(th)/sind(th))*x0 + (r / sind(th)); %// Note theta in degrees to respect your convention
%// Compute ending y coordinate
yend = (-cosd(th)/sind(th))*xend + (r / sind(th));
%// Draw the line
line([x0 xend], [y0 yend], 'Color', 'blue');
end
The above code is pretty simple. First, show the image using imshow in MATLAB. Next, use hold on so we can draw our lines in the image that will go on top of the image. Next, we calculate how many rho,theta pairs there are, and then we define the two x coordinates to be 1 and width as we will use these to determine where the starting and ending y coordinates are, given these x coordinates. Next, for each rho,theta pair we have, determine the corresponding y coordinates, then use line to draw a line from the starting and ending (x,y) coordinates in blue. We repeat this until we run out of lines.
Don't be alarmed if the y coordinates that are produced go out of bounds in the image. line will be intelligent enough to simply cap the result.
When theta = 0
The above code works assuming that you have no vertical lines detected in the Hough Transform, or when theta = 0. If theta = 0 (like in your case), this means that we have a vertical line which would thus produce an infinite slope and our formulation of y = mx + b is invalid. Should theta = 0, the equation of the line becomes x = rho. As such, you will need an additional if statement inside your loop that will detect this:
imshow(im); %// Show the image
hold on; %// Hold so we can draw lines
numLines = numel(rho); %// or numel(theta);
%// These are constant and never change
x0 = 1;
xend = size(im,2); %// Get the width of the image
%// For each rho,theta pair...
for idx = 1 : numLines
r = rho(idx); th = theta(idx); %// Get rho and theta
%// if a vertical line, then draw a vertical line centered at x = r
if (th == 0)
line([r r], [1 size(im,1)], 'Color', 'blue');
else
%// Compute starting y coordinate
y0 = (-cosd(th)/sind(th))*x0 + (r / sind(th)); %// Note theta in degrees to respect your convention
%// Compute ending y coordinate
yend = (-cosd(th)/sind(th))*xend + (r / sind(th));
%// Draw the line
line([x0 xend], [y0 yend], 'Color', 'blue');
end
end
In order to draw the vertical line, I need to know how high the image is so that we can draw a vertical line from the top of the image (y = 1) down to the bottom of the image (y = height) which is anchored at x = rho. As such, the above code should now properly handle any line, as well as the degenerate case when the slope is infinite. Therefore, this second version of the code is what you're after.
Good luck!
I am trying to sort random coordinates on a 2D cartesian grid using MATLAB into "bins" defined by a grid.
For example if I have a 2D domain with X ranging from [-1,1] and Y from [-1,1] and I generate some random coordinates within the domain, how can I "count" how many coordinates fall into each quadrant?
I realize that for and if statements can be used to determine the if each coordinate is within the quadrants, but I would like to scale this to much larger square grids that have more than just 4 quadrants.
Any concise and efficient approach would be appreciated!
Below is an example adapted from the code I mentioned.
The resulting binned points are be stored the variable subs; Each row contains 2d subscript indices of the bin to which a point was assigned.
% 2D points, both coordinates in the range [-1,1]
XY = rand(1000,2)*2 - 1;
% define equal-sized bins that divide the [-1,1] grid into 10x10 quadrants
mn = [-1 -1]; mx = [1 1]; % mn = min(XY); mx = max(XY);
N = 10;
edges = linspace(mn(1), mx(1), N+1);
% map points to bins
% We fix HISTC handling of last edge, so the intervals become:
% [-1, -0.8), [-0.8, -0.6), ..., [0.6, 0.8), [0.8, 1]
% (note the last interval is closed on the right side)
[~,subs] = histc(XY, edges, 1);
subs(subs==N+1) = N;
% 2D histogram of bins count
H = accumarray(subs, 1, [N N]);
% plot histogram
imagesc(H.'); axis image xy
set(gca, 'TickDir','out')
colormap gray; colorbar
xlabel('X'); ylabel('Y')
% show bin intervals
ticks = (0:N)+0.5;
labels = strtrim(cellstr(num2str(edges(:),'%g')));
set(gca, 'XTick',ticks, 'XTickLabel',labels, ...
'YTick',ticks, 'YTickLabel',labels)
% plot 2D points on top, correctly scaled from [-1,1] to [0,N]+0.5
XY2 = bsxfun(#rdivide, bsxfun(#minus, XY, mn), mx-mn) * N + 0.5;
line(XY2(:,1), XY2(:,2), 'LineStyle','none', 'Marker','.', 'Color','r')
I am trying to convert an image from cartesian to polar coordinates.
I know how to do it explicitly using for loops, but I am looking for something more compact.
I want to do something like:
[x y] = size(CartImage);
minr = floor(min(x,y)/2);
r = linspace(0,minr,minr);
phi = linspace(0,2*pi,minr);
[r, phi] = ndgrid(r,phi);
PolarImage = CartImage(floor(r.*cos(phi)) + minr, floor(r.sin(phi)) + minr);
But this obviously doesn't work.
Basically I want to be able to index the CartImage on a grid.
The polar image would then be defined on the grid.
given a matrix M (just a 2d Gaussian for this example), and a known origin point (X0,Y0) from which the polar transform takes place, we expect that iso-intensity circles will transform to iso-intensity lines:
M=fspecial('gaussian',256,32); % generate fake image
X0=size(M,1)/2; Y0=size(M,2)/2;
[Y X z]=find(M);
X=X-X0; Y=Y-Y0;
theta = atan2(Y,X);
rho = sqrt(X.^2+Y.^2);
% Determine the minimum and the maximum x and y values:
rmin = min(rho); tmin = min(theta);
rmax = max(rho); tmax = max(theta);
% Define the resolution of the grid:
rres=128; % # of grid points for R coordinate. (change to needed binning)
tres=128; % # of grid points for theta coordinate (change to needed binning)
F = TriScatteredInterp(rho,theta,z,'natural');
%Evaluate the interpolant at the locations (rhoi, thetai).
%The corresponding value at these locations is Zinterp:
[rhoi,thetai] = meshgrid(linspace(rmin,rmax,rres),linspace(tmin,tmax,tres));
Zinterp = F(rhoi,thetai);
subplot(1,2,1); imagesc(M) ; axis square
subplot(1,2,2); imagesc(Zinterp) ; axis square
getting the wrong (X0,Y0) will show up as deformations in the transform, so be careful and check that.
I notice that the answer from bla is from polar to cartesian coordinates.
However the question is in the opposite direction.
I=imread('output.png'); %read image
I1=flipud(I);
A=imresize(I1,[1024 1024]);
A1=double(A(:,:,1));
A2=double(A(:,:,2));
A3=double(A(:,:,3)); %rgb3 channel to double
[m n]=size(A1);
[t r]=meshgrid(linspace(-pi,pi,n),1:m); %Original coordinate
M=2*m;
N=2*n;
[NN MM]=meshgrid((1:N)-n-0.5,(1:M)-m-0.5);
T=atan2(NN,MM);
R=sqrt(MM.^2+NN.^2);
B1=interp2(t,r,A1,T,R,'linear',0);
B2=interp2(t,r,A2,T,R,'linear',0);
B3=interp2(t,r,A3,T,R,'linear',0); %rgb3 channel Interpolation
B=uint8(cat(3,B1,B2,B3));
subplot(211),imshow(I); %draw the Original Picture
subplot(212),imshow(B); %draw the result