OpenGL de プログラミング - Bresenhamのアルゴリズムでの直線
現在地 >> メニュー >> サンプルコード::OpenCV >> Bresenhamのアルゴリズムでの直線

問題


背景の黒のウィンドウ(300×300)を作成し、Bresenhamのアルゴリズムを用いて、
(50,50)ー(250,200)間に白い直線を描画せよ。

参考
http://web.joetsu.ne.jp/~hos/kouryaku/CG2-5.htm
http://en.wikipedia.org/wiki/Bresenham's_line_algo...

 →Bresenhamのアルゴリズムでの直線2

答え


#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <cmath>

using namespace std;


CvSize window={300,300};//ウィンドウサイズ

int main( int argc, char **argv)
{

IplImage *imgA = cvCreateImage(window,IPL_DEPTH_8U,3);
cvSet (imgA, cvScalarAll (0), 0);

int xx1,yy1,xx2,yy2;
int dx,dy,a,a1,e;

int x,y;

xx1 = 50,yy1=50;
xx2 = 250,yy2 = 200;

dx = abs(xx2 - xx1);
dy = abs(yy2 - yy1);

y = yy1;
x = xx1;
int sx,sy;

if(xx1>xx2)
{
sx = -1;
}else
{
sx = 1;
}



if(yy1>yy2)
{
sy = -1;
}else
{
sy = 1;
}


if(dx>=dy){
a = 2*dy;
a1= a-2*dx;
e = a - dx;

for(x = xx1; (sx >=0 ? x<= xx2 : x>=xx2) ;x+=sx)
{
imgA->imageData[y*imgA->widthStep + x*3] = (signed char)255;
imgA->imageData[y*imgA->widthStep + x*3+1] = (signed char)255;
imgA->imageData[y*imgA->widthStep + x*3+2] = (signed char)255;

if (e>=0)
{
y+=sy;
e += a1;
}else
{
e+=a;
}
}
}else
{
a = 2*dx;
a1= a-2*dy;
e = a - dy;
for(y = yy1; (sy >=0 ? y<= yy2 : y>=yy2) ;y+=sy)
{

imgA->imageData[y*imgA->widthStep + x*3] = (signed char)255;
imgA->imageData[y*imgA->widthStep + x*3+1] = (signed char)255;
imgA->imageData[y*imgA->widthStep + x*3+2] = (signed char)255;

if (e>=0)
{
x+=sx;
e += a1;
}else
{
e+=a;
}

}
}

cvNamedWindow("window",CV_WINDOW_AUTOSIZE);
cvShowImage("window",imgA);

cvWaitKey(0); // 0秒待つ => ずっと入力待ち

cvReleaseImage( &imgA );
cvDestroyWindow("window");

return 0;
}

メモ


名前は綴りからすると「ブ」レゼンハムのようだ。