Brenham算法——matlab实现
功能甄宓
根据两点进⾏直线插补
⽀持不在图像中的点的插补,即对输⼊的两个点进⾏拟合,拟合直线上的点如果在图像范围内,则修改图像对应的像素值实现代码
Brenham 算法可以保证图像的连通度,其实现⽅法如下:
function [ img , runTime ] = MyBrenhamDrawLine( img , x1 , y1 , x2 , y2 , lColor )
% Brenham直线画线算法,img的图像背景为⿊⾊,img为输⼊的图像,
% (x1,y1)为第⼀个点的坐标,x1是矩阵的⾏的位置,⽽⾮屏幕坐标系的定义
% (x2,y2)为第⼆个点的坐标
% lColor : 插补的直线的颜⾊的灰度值,默认是1,即⽩⾊
% 如果没有指定具体的颜⾊,则直线在图中默认是⽩⾊
八月最后一天if nargin < 6
lColor = 1;
end
if ~ismatrix(img)毛竹
error('------------can not deal with 3-dims data--------');
end
tic
[height, width] = size( img );
if x1>0 && x1<=height && y1>0 && y1<=width
img(x1,y1) = lColor;
end
if x2>0 && x2<=height && y2>0 && y2<=width
img(x2,y2) = lColor;
end
k = (y1-y2)/(x1-x2);
星期五晚上flag = 1;
if abs(k) > 1
[x1, y1] = SwapXY( y1, x1 );
[x2, y2] = SwapXY( y2, x2 );
k = 1/k;
flag = 0;
这就是爱吧
end
if x1 > x2
[x1, x2] = SwapXY(x2, x1);
[y1, y2] = SwapXY(y2, y1);
end
deltaX = x2 - x1;
deltaY = abs(y2 - y1);
p = 2*deltaY - deltaX;
minX = min(x1, x2);
maxX = max(x1, x2);
yk = y1;
for ii = minX : maxX-1
if p < 0
p = p + 2 * deltaY;
el景区营销
if k > 0
yk = yk + 1;
el
yk = yk - 1;
end
p = p + 2 * deltaY - 2 * deltaX;
end
if flag
if ii+1>0 && ii+1<=height && yk>0 && yk<=width img(ii+1,yk) = lColor;
end
el
if ii+1>0 && ii+1<width && yk>0 && yk<height img(yk,ii+1) = lColor;
end
end生日蛋糕画
end
runTime = toc;
end
function [y, x]=SwapXY(x1,y1)
x=y1;
y=x1;
end
结果图
竞选学生会主席img = zeros(500);
img=MyBrenhamDrawLine(img,200, 500,600,400); imtool(img)