您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 广告经营 > 直线扫描转换代码-MATLAB
一、直线扫描转换%file1.m文件,这是主文件%x=0,y=0,r=1;%Bresenhamcircle(x,y,r);clearall;clc;p1=[19820];p2=[-16092370];%Line_Scanner_DDA(p1(1),p1(2),p2(1),p2(2));%Line_Scanner_Bresenham(p1,p2);line_Bresenham(p1,p2);line_DDA(p1,p2);%x=[3.12-3.6];%ceil(x)%line_Bresenham.m文件,实现直线扫描转换的bresenham算法functionline_Bresenham(p1,p2)XX=p2(1)-p1(1);YY=p2(2)-p1(2);XYSwitch=0;%表示x和y是否交换,1表示需要交换YSign=1;%表示YY的符号,-1表示经过了y--y的转换ifXX*YY==0ifYY==0t=sort([p1(1),p2(1)]);Point(:,1)=(t(1):t(2))';Point(:,2)=zeros(t(2)-t(1)+1,1)+p1(2);elset=sort([p1(2),p2(2)]);Point(:,2)=(t(1):t(2))';Point(:,1)=zeros(t(2)-t(1)+1,1)+p1(1);endelse%如果斜率的绝对值大于1,则交换x和yifabs(YY)abs(XX)XYSwitch=1;t(1)=p1(1);p1(1)=p1(2);p1(2)=t(1);t(1)=p2(1);p2(1)=p2(2);p2(2)=t(1);end%如果x1x2则交换p1和p2ifp1(1)p2(1)t=[p1(1),p1(2)];p1=[p2(1),p2(2)];p2=t;endXX=p2(1)-p1(1);YY=p2(2)-p1(2);%如果y1y2,则做y--y的转换ifYY0p1(2)=-p1(2);p2(2)=-p2(2);YSign=-1;endYY=p2(2)-p1(2);%开始计算点d=XX-2*YY;P=[p1(1),p1(2)];k=1;whileP(1)=p2(1)Point(k,:)=P;ifd0P=P+ones(1,2);d=d+2*XX-2*YY;elseP(1)=P(1)+1;d=d-2*YY;endk=k+1;end%恢复点ifYSign==-1Point(:,2)=-Point(:,2);endifXYSwitch==1t=Point(:,1);Point(:,1)=Point(:,2);Point(:,2)=t;endend%绘制点figure();scatter(Point(:,1),Point(:,2),2,'.');legend('Bresenham算法');%line_DDA.m文件,实现直线扫描转换的数值微分算法functionline_DDA(P1,P2)p1=[P1(1),P1(2)];p2=[P2(1),P2(2)];XY=p2-p1;%x轴和y轴增量XYSwitch=0;%标记P1和P2的x和y是否交换过,1表示需要交换YSign=1;%标记y轴增量符号,-1表示需要进行y--y的转换ifXY(1)*XY(2)==0ifXY(1)==0t=sort([p1(2),p2(2)]);Point(:,2)=(t(1):t(2))';Point(:,1)=zeros(t(2)-t(1)+1,1)+p1(1);elset=sort([p1(1),p2(1)]);Point(:,1)=(t(1):t(2))';Point(:,2)=zeros(t(2)-t(1)+1,1)+p1(2);endelse%如果斜率的绝对值大于1,则交换x和yifabs(XY(2))abs(XY(1))XYSwitch=1;t(1)=p1(1);p1(1)=p1(2);p1(2)=t(1);t(1)=p2(1);p2(1)=p2(2);p2(2)=t(1);end%如果x1x2,则交换p1和p2ifp1(1)p2(1)t=p1;p1=p2;p2=t;endXY=p2-p1;%如果y1y2,则做y--y的转换ifXY(2)0p1(2)=-p1(2);p2(2)=-p2(2);YSign=-1;endXY=p2-p1;%开始计算k=XY(2)/XY(1);Point(:,1)=(p1(1):p2(1))';Point(:,2)=round((0:abs(XY(1)))'*k+p1(2));%恢复变换ifYSign==-1Point(:,2)=-Point(:,2);endifXYSwitch==1t=Point(:,1);Point(:,1)=Point(:,2);Point(:,2)=t;endend%将计算得到的点画出来figure();scatter(Point(:,1),Point(:,2),2,'.');legend('DDA算法');
本文标题:直线扫描转换代码-MATLAB
链接地址:https://www.777doc.com/doc-4489924 .html