extend line to edge of image in matlab

To extend a line to the edge of an image in Matlab, you can use the improfile function to sample pixel values along the line, and then interpolate to estimate pixel values at points outside the image boundaries. Here's an example:

main.m
% Load an image and detect edges
img = imread('example.png');
BW = edge(img, 'canny');

% Define a line segment
x0 = 50; y0 = 50;
x1 = 100; y1 = 100;

% Sample pixel values along the line
[pixel_vals, ~] = improfile(BW, [x0, x1], [y0, y1]);

% Compute the length of the line segment
len = norm([x1-x0, y1-y0]);

% Define points outside the image boundaries
x_out = [-len, 2*len] + x0;
y_out = [y0, y0];

% Interpolate to estimate pixel values at the outer points
f = griddedInterpolant([-(len+1), 0, len+1], [0, len/2, len]);
vals_out = f(pixel_vals);

% Plot the result
figure; imshow(BW); hold on;
plot([x0, x1], [y0, y1], 'r-', 'LineWidth', 2);
plot(x_out, y_out, 'gx');
plot(x_out, y_out, 'bo', 'MarkerFaceColor', 'b');
plot(x_out, y_out + vals_out, 'b-', 'LineWidth', 2);
777 chars
29 lines

This code detects edges in an input image img using the Canny edge detector, and then defines a line segment from (x0,y0) to (x1,y1). It then samples pixel values along the line segment using the improfile function, and computes the length of the line segment. The code then defines two points outside the image boundaries (x_out), and uses a griddedInterpolant to interpolate pixel values at those points based on the sampled values. Finally, the code plots the original line segment, the sample points, and the extended line segment.

gistlibby LogSnag