extend line made of two points across whole image in matlab

To extend a line segment made of two points across the whole image, you need to perform the following steps:

  1. Find the slope (m) and y-intercept (b) of the line segment using the two points.
  2. Determine the coordinates of the two intersection points of the line and the image border.
  3. Draw a line between these two intersection points using the line function in Matlab.

Here is the code to achieve this:

main.m
% read the image
img = imread('your_image_path');

% define the two points of the line segment
pt1 = [x1, y1];
pt2 = [x2, y2];

% calculate slope and y-intercept of the line segment
m = (pt2(2)-pt1(2))/(pt2(1)-pt1(1));
b = pt1(2) - m*pt1(1);

% determine the image border coordinates
[img_height, img_width, ~] = size(img);
x_left = 1;
y_left = m*x_left + b;
x_right = img_width;
y_right = m*x_right + b;
x_top = (1-b)/m;
y_top = 1;
x_bottom = (img_height-b)/m;
y_bottom = img_height;

% find intersection points inside the image boundary
int_pts = [x_left, y_left; x_right, y_right; x_top, y_top; x_bottom, y_bottom];
int_pts = int_pts(all(int_pts>=1 & int_pts<=repmat([img_width,img_height], size(int_pts,1), 1), 2),:);

% draw the extended line on the image
imshow(img);
hold on;
line(int_pts(:,1), int_pts(:,2));
hold off;
827 chars
32 lines

This code will find the intersection points of the line and the image border, then draw a line between them over the original image.

gistlibby LogSnag