Matlab manipulate edges - matlab

I'm working on an image processing project. I have a grayscale image and detected edges with Canny edge detection. Now I would like to manipulate the result by filtering the unnecessary edges. I would like to keep the edges which are close to horizontal and delete edges which are close to vertical.
How can I delete the close to vertical edges?

One option is to use half of a Sobel operator. The full algorithm finds horizontal and vertical edges, then combines them. You are only interested in horizontal edges, so just compute that part (which is Gy in the Wikipedia article).
You may also want to threshold the result to get a black and white image instead of shades of gray.
You could apply this technique to the original grayscale image or the result of the Canny edge detection.

It depends on how cost-intensive it is allowed to be. One easy way to do would be:
(1) Convolute your image with Sobel-Filters (gives Dx, Dy).
For each canny-edge-pixel:
(2) Normalize (Dx, Dy), s.t. in every pixel you have the direction of your edge.
(3) Compute the inner products with the direction you want to remove (in your case (0,1)).
(4) If the absolut value of the inner product is smaller than some threshold remove the pixel.
Example:
img = ...;
canny_img = ...;
removeDir = [0;1];
% convolute with sobel masks
sobelX = [1, 0, -1; 2, 0, -2; 1, 0, -1];
sobelY = sobelX';
DxImg = conv2(img,sobelX,'same');
DyImg = conv2(img,sobelY,'same');
% for each canny-edge-pixel:
for lin = 1:size(img,1) % <-> y
for col = 1:size(img,2) % <-> x
if canny_img(lin,col)
% normalize direction
normDir = [DxImg(lin,col); DyImg(lin,col)];
normDir = normDir / norm(normDir,2);
% inner product
innerP = normDir' * removeDir;
% remove edge?
if abs(innerP) < cos(45/180*pi) % 45° threshold
canny_img(lin,col) = 0;
end
end
end
end
You can optimize it a lot due to your requirements.

Related

Detect endpoints of a line

I want to detect the points shown in the image below:
I have done this so far:
[X,map] = rgb2ind(img,0.0);
img = ind2gray(X,map); % Convert indexed to grayscale
level = graythresh(img); % Compute an appropriate threshold
img_bw = im2bw(img,level);% Convert grayscale to binary
mask = zeros(size(img_bw));
mask(2:end-2,2:end-2) = 1;
img_bw(mask<1) = 1;
%invert image
img_inv =1-img_bw;
% find blobs
img_blobs = bwmorph(img_inv,'majority',10);
% figure, imshow(img_blobs);
[rows, columns] = size(img_blobs);
for col = 1 : columns
thisColumn = img_blobs(:, col);
topRow = find(thisColumn, 1, 'first');
bottomRow = find(thisColumn, 1, 'last');
img_blobs(topRow : bottomRow, col) = true;
end
inverted = imcomplement(img_blobs);
ed = edge(inverted,'canny');
figure, imshow(ed),title('inverted');
Now how to proceed to get the coordinates of the desired position?
The top point is obviously the white pixel with the highest ordinate, which is easily obtained.
The bottom point is not so well defined. What you can do is
follow the peak edges until you reach a local minimum, on the left and on the right. That gives you a line segment, which you can intersect with the vertical through the top point.
if you know a the peak width, try every pixel on the vertical through the top point, downward, and stop until it has no left nor right neighbors at a distance equal to the peak with.
as above, but stop when the distance between the left and right neighbors exceeds a threshold.
In this particular case, you could consider using houghlines in matlab. Setting the required Theta and MinLength parameter values, you should be able to get the two vertical lines parallel to your peak. You can use the end points of the vertical lines, to get the point at the bottom.
Here is a sample code.
[H,theta,rho] = hough(bw,'Theta',5:1:30);%This is the angle range
P = houghpeaks(H,500,'NHoodSize',[11 11]);
lines = houghlines(bw,theta,rho,P,'FillGap',10,'MinLength',300);
Here is a complete description of how houghlines actually works.

Orientational Canny Edge Detection

I want to detect edges using Canny method. In the end I want two edge maps: 1 for horizontal 1 for vertical direction.
In MATLAB this can be achieved by using Sobel or Prewitt operators with an extra direction argument, but for Canny we do not have this option.
E = edge(I,'Sobel','horizontal')
Any idea how to extract both horizontal and vertical edges, separately, by using Canny?
There is no way using the built in edge function. However, Canny edge detection uses the angles from the Sobel Operator. It is very easy to reproduce these values.
Start with an image, I'll use a built in demo image.
A = im2double(rgb2gray(imread('peppers.png')));
Get the Canny edges
A_canny = edge(A, 'Canny');
Sobel Operator -- We can't use the built in implementation (edge(A_filter, 'Sobel')), because we want the edge angles, not just the edge locations, so we implement our own operator.
a. Gaussian filter. This is a preprocessing step for Canny, so we should probably reproduce it here
A_filter = imgaussfilt(A);
b. Convolution to find oriented gradients
%These filters measure the difference in values between vertically or horizontally adjacent pixels.
%Effectively, this finds vertical and horizontal gradients.
vertical_filter = [-1 0 1; -2 0 2; -1 0 1];
horizontal_filter = [-1 -2 -1; 0 0 0; 1 2 1];
A_vertical = conv2(A_filter, vertical_filter, 'same');
A_horizontal = conv2(A_filter, horizontal_filter, 'same');
c. Calculate the angles
A_angle = arctan(A_vertical./A_horizontal);
Get the angle values at the edge locations
A_canny_angles = nan(size(A));
A_canny_angles(A_canny) = A_angle(A_canny);
Choose the angles that you are interested in
angle_tolerance = 22.5/180*pi;
target_angle = 0;
A_target_angle = A_canny_angles >= target_angle*pi/180 - angle_tolerance & ...
A_canny_angles<= target_angle*pi/180 + angle_tolerance;
So if I'm looking for horizontal lines, my target angle would be zero. The image below illustrates steps 1, 2, 4 and 5. The final result of the extracted horizontal lines is shown in the bottom right. You can see that they are not exactly horizontal because I used such a large angle tolerance window. This is a tunable parameter depending on how exactly you want to hit your target angle.

Edge detection at a certain degree using canny method

I am using MATLAB. I want to use canny method for edge detection. But I need the edges that are diagonal or the edges that are only on 40 to 50 degree angle. how can i do that?
You need write canny edge detector's code by your own (you would get lots of implementation )in the internet. You would then be calculating the gradient magnitudes and gradient directions in the second step. There you need to filter out the angles and corresponding magnitudes.
Hope this helps you.
I've answered a similar question about how to use Matlab's edge function to find oriented edges with Canny ( Orientational Canny Edge Detection ), but I also wanted to try out a custom implementation as suggested by Avijit.
Canny Edge Detection steps:
Start with an image, I'll use a built in demo image.
A = im2double(rgb2gray(imread('peppers.png')));
Gaussian Filter
A_filter = imgaussfilt(A);
Sobel Edge Detection -- We can't use the built in implementation (edge(A_filter, 'Sobel')), because we want the edge angles, not just the edge locations, so we implement our own operator.
a. Convolution to find oriented gradients
%These filters measure the difference in values between vertically or horizontally adjacent pixels.
%Effectively, this finds vertical and horizontal gradients.
vertical_filter = [-1 0 1; -2 0 2; -1 0 1];
horizontal_filter = [-1 -2 -1; 0 0 0; 1 2 1];
A_vertical = conv2(A_filter, vertical_filter, 'same');
A_horizontal = conv2(A_filter, horizontal_filter, 'same');
b. Calculate the angles
A_angle = arctan(A_vertical./A_horizontal);
At this step, we traditionally bin edges by orientation (0°, 45°, 90°, 135°), but since you only want diagonal edges between 40 and 50 degrees, we will retain those edges and discard the rest.
% I lowered the thresholds to include more pixels
% But for your original post, you would use 40 and 50
lower_angle_threshold = 22.5;
upper_angle_threshold = 67.5;
diagonal_map = zeros(size(A), 'logical');
diagonal_map (A_angle>(lower_angle_threshold*pi/180) & A_angle<(upper_angle_threshold*pi/180)) = 1;
Perform non-max suppression on the remaining edges -- This is the most difficult portion to adapt to different angles. To find the exact edge location, you compare two adjacent pixels: for 0° edges, compare east-west, for 45° south-west pixel to north-east pixel, for 90° compare north-south, and for 135° north-west pixel to south-east pixel.
Since your desired angle is close to 45°, I just used south-west, but if you wanted 10° to 20°, for example, you'd have to put some more thought into these comparisons.
non_max = A_sobel;
[n_rows, n_col] = size(A);
%For every pixel
for row = 2:n_rows-1
for col = 2:n_col-1
%If we are at a diagonal edge
if(diagonal_map(row, col))
%Compare north east and south west pixels
if(A_sobel(row, col)<A_sobel(row-1, col-1) || ...
A_sobel(row, col)<A_sobel(row+1, col+1))
non_max(row, col) = 0;
end
else
non_max(row, col) = 0;
end
end
end
Edge tracking with hysteresis -- Decide whether weak edge pixels are close enough (I use a 3x3 window) to strong edge pixels. If they are, include them in the edge. If not, they are noise; remove them.
high_threshold = 0.5; %These thresholds are tunable parameters
low_threshold = 0.01;
weak_edge_pixels = non_max > low_threshold & non_max < high_threshold;
strong_edge_pixels = non_max > high_threshold;
final = strong_edge_pixels;
for row = 2:n_rows-1
for col = 2:n_col-1
window = strong_edge_pixels(row-1:row+1, col-1:col+1);
if(weak_edge_pixels(row, col) && any(window(:)))
final(row, col) = 1;
end
end
end
Here are my results.
As you can see, discarding the other edge orientations has a very negative effect on the hysteresis step because fewer strong pixels are detected. Adjusting the high_threshold would help somewhat. Another option would be to do Steps 5 and 6 using all edge orientations, and then use the diagonal_map to extract the diagonal edges.

how to scale bounding box coordinates?

I'm extracting the outline of blob the following way:
bw = im2bw(image, threshold);
boundaries = bwboundaries(bw);
plot(boundaries(:, 2), boundaries(:, 1), 'k', 'LineWidth', 2);
what I would like to do now, is to scale boundaries so that I can plot a smaller version of the boundaries inside the original boundaries. Is there an easy way to do this?
Here's an example on what the result should look like: black is the original bounding box, and red is the same bounding box, just scaled (but with same center as black box).
EDIT:
I guess I can scale each point individually, but then I still have to recenter the coordinates. Is there a better way of doing this?
scale = 0.7
nbr_points = size(b, 1);
b_min = nan(nbr_points, 2);
for k = 1 : nbr_points
b_min(k, :) = ([scale 0; 0 scale] * b(k, 1:2)')';
end
Just creating a function which does this should be easy.
function scaledB = scaleBoundaries(B,scaleFactor)
% B is a cell array of boundaries. The output is a cell array
% containing the scaled boundaries, with the same center of mass
% as the input boundaries.
%%
for k = 1:length(B)
scaledB{k} = B{k} .* scaleFactor;
com = mean(B{k}); % Take the center of mass of each boundary
sCom = mean(scaledB{k}); % Take the center of mass of each scaled boundary
difference = com-sCom; % Difference between the centers of mass
% Recenter the scaled boundaries, by adding the difference in the
% centers of mass to the scaled boundaries:
scaledB{k}(:,1) = scaledB{k}(:,1) + difference(1);
scaledB{k}(:,2) = scaledB{k}(:,2) + difference(2);
end
end
Or did you want to avoid something unoptimized for speed purposes?

Stretching an ellipse in an image to form a circle

I want to stretch an elliptical object in an image until it forms a circle. My program currently inputs an image with an elliptical object (eg. coin at an angle), thresholds and binarizes it, isolates the region of interest using edge-detect/bwboundaries(), and performs regionprops() to calculate major/minor axis lengths.
Essentially, I want to use the 'MajorAxisLength' as the diameter and stretch the object on the minor axis to form a circle. Any suggestions on how I should approach this would be greatly appreciated. I have appended some code for your perusal (unfortunately I don't have enough reputation to upload an image, the binarized image looks like a white ellipse on a black background).
EDIT: I'd also like to apply this technique to the gray-scale version of the image, to examine what the stretch looks like.
code snippet:
rgbImage = imread(fullFileName);
redChannel = rgbImage(:, :, 1);
binaryImage = redChannel < 90;
labeledImage = bwlabel(binaryImage);
area_measurements = regionprops(labeledImage,'Area');
allAreas = [area_measurements.Area];
biggestBlobIndex = find(allAreas == max(allAreas));
keeperBlobsImage = ismember(labeledImage, biggestBlobIndex);
measurements = regionprops(keeperBlobsImage,'Area','MajorAxisLength','MinorAxisLength')
You know the diameter of the circle and you know the center is the location where the major and minor axes intersect. Thus, just compute the radius r from the diameter, and for every pixel in your image, check to see if that pixel's Euclidean distance from the cirlce's center is less than r. If so, color the pixel white. Otherwise, leave it alone.
[M,N] = size(redChannel);
new_image = zeros(M,N);
for ii=1:M
for jj=1:N
if( sqrt((jj-center_x)^2 + (ii-center_y)^2) <= radius )
new_image(ii,jj) = 1.0;
end
end
end
This can probably be optimzed by using the meshgrid function combined with logical indices to avoid the loops.
I finally managed to figure out the transform required thanks to a lot of help on the matlab forums. I thought I'd post it here, in case anyone else needed it.
stats = regionprops(keeperBlobsImage, 'MajorAxisLength','MinorAxisLength','Centroid','Orientation');
alpha = pi/180 * stats(1).Orientation;
Q = [cos(alpha), -sin(alpha); sin(alpha), cos(alpha)];
x0 = stats(1).Centroid.';
a = stats(1).MajorAxisLength;
b = stats(1).MinorAxisLength;
S = diag([1, a/b]);
C = Q*S*Q';
d = (eye(2) - C)*x0;
tform = maketform('affine', [C d; 0 0 1]');
Im2 = imtransform(redChannel, tform);
subplot(2, 3, 5);
imshow(Im2);