이번에는 메인클래스안에서 처리하는 방법이다.

MyFrame 클래스에서 스윙을 상속받고 리스너 인터페이스까지 사용한다.




MyFrame

 

import javax.swing.*;

import java.awt.event.*;

 

public class MyFrame extends JFrame implements ActionListener

{

    private JPanel panel;

    private JButton b1;

    private JButton b2;

    private JLabel l1;

    private JTextField t1;

    private JTextField t2;

   

 

    public MyFrame()

    {       

         this.setSize(300, 150);

         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         this.setTitle("연습~");

         panel = new JPanel();

         b1 = new JButton("원의 둘레");

         b2 = new JButton("원의 면적");

         l1 = new JLabel("반지름의 길이를 입력해주세요:");

         t1 = new JTextField(5);

         t2 = new JTextField(10);        

         b1.addActionListener(this); //현재 객체를 리스너로 등록하였다.

         b2.addActionListener(this);        

         panel.add(l1);

         panel.add(t1);

         panel.add(b1);

         panel.add(b2);

         panel.add(t2);

         this.add(panel);

         this.setVisible(true);

    }    

   

    public void actionPerformed(ActionEvent e)

    {

        double d;

       

        if(e.getSource()==b1)

        {

            d = Double.parseDouble(t1.getText());

            t2.setText(Double.toString(d *3.14));

        }

        else if(e.getSource()==b2)

        {

            d = Double.parseDouble(t1.getText());

            t2.setText(Double.toString(d *d * 3.14));

        }

    }

}

Posted by 아몰라
이번에는 내부클래스로 만들어서 해보았다.




클래스 하나가 MyFrame으로 들어왔다...

Action클래스가 MyFrame클래스안에 들어옴으로써 private변수들 때문에 만들었던 get set 함수가 필요없어졌다.

외부클래스의 멤버변수들을 자유롭게 사용한다.


MyFrame

public class MyFrame extends JFrame

{

    private JPanel panel;

    private JButton b1;

    private JButton b2;

    private JLabel l1;

    private JTextField t1;

    private JTextField t2;

   

 

    public MyFrame()

    {       

         this.setSize(300, 150);

         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         this.setTitle("연습~");

         panel = new JPanel();

         b1 = new JButton("원의 둘레");

         b2 = new JButton("원의 면적");

         l1 = new JLabel("반지름의 길이를 입력해주세요:");

         t1 = new JTextField(5);

         t2 = new JTextField(10);        

         b1.addActionListener(new MyActionHandler());

         b2.addActionListener(new MyActionHandler());        

         panel.add(l1);

         panel.add(t1);

         panel.add(b1);

         panel.add(b2);

         panel.add(t2);

         this.add(panel);

         this.setVisible(true);

    }

   

    Private class MyActionHandler  implements ActionListener
{       

 

   

    public void actionPerformed(ActionEvent e)

    {

        double d;

       

        if(e.getSource()==b1)

        {

            d = Double.parseDouble(t1.getText());

            t2.setText(Double.toString(d *3.14));

        }

        else if(e.getSource()==b2)

        {

            d = Double.parseDouble(t1.getText());

            t2.setText(Double.toString(d *d * 3.14));

        }

    }

   

}

   

}


Posted by 아몰라





 프로그램설명 - 반지름의 값을 적고...원 둘레와 원의 면적 버튼을 누를시 아래 텍스트필드에 그 값이 나오게 하여라.


1. 먼저 이벤트는 어떠한 행동을 하였을때 발생하는 액션리스너를 이용하였다.

2. 액션리스너를 상속받는 클래스는 외부클래스로 두었다.(이 밖에 내부클래스로 사용하는법과 그 안에 메인클래스에 함수로 사용하는법 세가지가 있다.)

3. 그리하여 총 3개의 클래스로 만들었다.

MyFrame클래스 - 스윙을 이용하여 GUI 환경의 컴포넌트들을 만들고 이벤트를 등록한다.

MyActionHandle 클래스 - 이벤트 발생시 발생되는 행동들이 실행하는 클래스.

MyFrameTest클래스 - 프로그램을 시작한다.




MyActionHandle

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

 

public class MyActionHandler  implements ActionListener //액션인터페이스를 사용

{

    private MyFrame f;  

   

    public MyActionHandler(MyFrame f) //포인터로 MyFrame클래스를 가져온다.

    {

        this.f = f;

    }   

    public void actionPerformed(ActionEvent e)

    {

        double d;       

        if(e.getSource()==f.getButton())

        {

            d = Double.parseDouble(f.getTextField());

            f.setTextField(d *3.14);

        }

        else if(e.getSource()==f.getButton2())

        {

            d = Double.parseDouble(f.getTextField());

            f.setTextField(d*d*3.14);

        }

    }   

}

MyFrame

import javax.swing.*;

 

public class MyFrame extends JFrame //JFrame을 상속받는다.

{

    private JPanel panel;

    private JButton b1;

    private JButton b2;

    private JLabel l1;

    private JTextField t1;

    private JTextField t2;

 

    public JButton getButton(){ //MyFrameprivate 변수로 인해 get set 함수만들기

            return b1;

        }       

    public JButton getButton2(){

            return b2;

        }       

    public String getTextField(){

            return t1.getText();

        }   

    public void setTextField(Double d){

            t2.setText(Double.toString(d));

    }     

 

    public MyFrame()

    {       

         setSize(300, 150);

         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         setTitle("연습~");

         panel = new JPanel();

         b1 = new JButton("원의 둘레");

         b2 = new JButton("원의 면적");

         l1 = new JLabel("반지름의 길이를 입력해주세요:");

         t1 = new JTextField(5);

         t2 = new JTextField(10);        

         MyActionHandler han = new MyActionHandler(this); //리스너클래스 생성

         b1.addActionListener(han); //리스너등록

         b2.addActionListener(han);        

         panel.add(l1);

         panel.add(t1);

         panel.add(b1);

         panel.add(b2);

         panel.add(t2);

         add(panel);

         setVisible(true);

    }    

}

 

MyFrameTest

public class MyFrameTest

{

    public static void main(String[] args)

    {

        MyFrame my = new MyFrame();

    }

}


Posted by 아몰라

출처 - http://kimhj8574.egloos.com/4734597



*** IplImage 관련,  생성과 해제 등

//생성
IplImage *srcimg_R  = NULL;
srcimg_R  = cvCreateImage(cvSize(m_width,m_height), 8, 3);   //cvSize(640,480) 같은 것도 됨
srcimg_R  = cvCreateImage(cvGetSize(src_color), 8, 3);           //요것도 됨.  다른 IplImage 사이즈 받아와서

//요런것도 됨
CvSize img_size;   
img_size.height = ImageHeight;
img_size.width  = ImageWidth;

IplImage* BGR_image = cvCreateImage(img_size, IPL_DEPTH_8U, 3);

//이미지 복사하기
src = cvCloneImage(src_img);  //src가 비어있어야 함.  아니면 메모리 계속 쌓인다
cvCopy(src_img, src_img2);

//0으로 초기화
cvZero(src_img);

//해제
if(srcimg_R)
  cvReleaseImage(&srcimg_R);




*** IplImage 안의 이미지 화소 조절하기

* 간단하지만 속도가 좀 느린 방법
cvGetReal2D(srcimg, i, j);             //높이가 i, 폭이 j
cvSetReal2D(srcimg, i, j, value);    //value는 설정할 값

 


* 약간 복잡하지만 속도가 빠른 방법 (추가)

for(h=0; h<img->height; ++h)

{

     BYTE* pData = (BYTE*)(img->imageData + h*imgData->widthStep);

     for(w=0; w<img->width; ++w)

     {

          // gray image

          BYTE valGray = pData[w];    

 

          // color image (BGR 순서입니다.)

          BYTE valB = pData[w*3];

          BYTE valG = pData[w*3+1];

          BYTE valR = pData[w*3+2];

     }

}




*** 이미지 불러오기, 저장하기
//불러오기
TmpLImg = cvLoadImage("img_InElevator_1_L.bmp");    //간단하게, TmpLImg는 IplImage

//복잡하게
if ((TmpLImg = cvLoadImage("img_InElevator_1_L.bmp")) == 0)  // load left image
{
   printf("%s", "left image file read has failed!! \n");
   return 0;
}

//저장하기
char file_name[20];
sprintf(file_name,"img_R.bmp");            //파일이름 맹글기
cvSaveImage(file_name,srcimg_R);   //srcimg_R 이라는 IplImage를 저장




*** 창 만들고 닫기 등등
//생성
cvNamedWindow("Right Original", CV_WINDOW_AUTOSIZE);

//창 움직이기 - uv 좌표로 배치함
cvMoveWindow("source_color",610,0);

//보이기
cvShowImage( "Right Original", srcimg_R );

//창 닫기
cvDestroyAllWindows();  //모든 OpenCV 윈도우 닫기

//특정 윈도우만 닫기
cvDestroyWindow("Right Original");




*** canny edge detect 사용하기
...
IplImage *canny_R   = NULL;
canny_R    = cvCreateImage(cvSize(m_width,m_height), 8, 1);
...
cvCvtColor(srcimg_R, grayimg_R, CV_BGR2GRAY);   //원본 컬러이미지를 흑백으로 변환하고
cvCanny( grayimg_R, canny_R, 40, 130, 3 );             //그 흑백이미지를 캐니로 변환




*** HLS 이미지로 변환하기
...
IplImage* src_hlsimg = cvCreateImage(cvSize(m_width,m_height), 8, 3);  //HLS 저장할 곳

//각 속성들 저장할 곳 선언
IplImage* Hue         = cvCreateImage(cvSize(m_width,m_height), 8, 1);
IplImage* Intensity   = cvCreateImage(cvSize(m_width,m_height), 8, 1);
IplImage* Saturation = cvCreateImage(cvSize(m_width,m_height), 8, 1);

cvCvtColor(srcimg, src_hlsimg, CV_BGR2HLS);   //src_hlsimg IplImage 구조체에 HLS 이미지 담긴다

cvCvtPixToPlane( src_hlsimg, Hue, Intensity, Saturation, NULL );  //HLS 이미지 각 속성별로 나눔
cvCvtPlaneToPix( Hue, Intensity, Saturation, NULL, hsvVideo2 );  //도로 합치기




*** 창으로 부터 키 입력 받기
...
pressed_key=cvWaitKey(0) ;
  if(pressed_key=='q')    //q 키가 누르면 빠져나가기
    break;
  else if(pressed_key=='c')  //캡쳐 키 누르면 캡쳐
  {
    timer=time(NULL);  //현재시간저장
    t=localtime(&timer); //지역시간
    sprintf(file_name,"img_%4d%02d%02d%02d%02d%2d.bmp",t->tm_year + 1900, t->tm_mon +1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); //파일이름 맹글기

    cvSaveImage(file_name, src_color);

    //확인메시지출력
    printf("%s file saved is success!!\n",file_name);
  }




*** 이미지 크기 줄이기

//생성
pEviMonitor = cvCreateImage(cvSize(m_pImgWidth, m_pImgHeight), IPL_DEPTH_8U, 1);
pEviMonitor2 = cvCreateImage(cvSize(m_pImgWidth/2, m_pImgHeight/2), IPL_DEPTH_8U, 1);  //  1/2 크기로 생성

//크기 줄이기
cvResize(pEviMonitor, pEviMonitor2, CV_INTER_LINEAR);  // For Resize




*** 화면에 글자 쓰기

char s_output_result[50];
CvFont font;
...
sprintf(s_output_result,"sum vector x:%1.3f  y:%1.3f",sumvector_x,sumvector_y );    //우선 sprintf로 문자열 생성
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, 0.5, 0.5, 0, 1);  //이런 저런 설정.
cvPutText(src_color, s_output_result ,cvPoint(15,20),&font,cvScalar(0,255,0));   //cvPoint로 글자 시작 위치 설정(uv)
//void cvInitFont(CvFont* font, int font_face, double hscale, double vscale, double italic_scale, int thickness)




*** 트랙바 생성

int hue_threshold=139;  //Hue 값의 피부색 threshold

cvNamedWindow( "HLS_image", CV_WINDOW_AUTOSIZE );
cvCreateTrackbar("Hue","HLS_image",&hue_threshold,255, NULL );  //중요한 부분은 요거




*** 마우스 입력

void on_mouse( int event, int x, int y, int flags, void* param );
......

cvSetMouseCallback( "LKTracker", on_mouse, NULL );
......

void on_mouse( int event, int x, int y, int flags, void* param )
{
    if( !image )
        return;

    if( image->origin )
        y = image->height - y;

    if( event == CV_EVENT_LBUTTONDOWN )
    {
        pt = cvPoint(x,y);
        add_remove_pt = 1;
    }
}




*** 인클루드 하는 것들

#include <cv.h>          //영상처리를 위한 헤더
#include <highgui.h>   //카메라로 영상을 입력받거나 이미지를 읽어들이고 화면에 보여주기 위한 헤더




*** good feature to track

IplImage *eig_image = NULL;
IplImage *temp_image = NULL;
eig_image  = cvCreateImage(cvSize(width,height), 32, 1);
temp_image = cvCreateImage(cvSize(width,height), 32, 1);

CvPoint2D32f frame1_features[4000];  //추출된 점들 저장하는 장소

int number_of_features; 
number_of_features = 400;  //추출되는 점의 개수를 제한

//안됨.  버전마다 매개변수 다른듯
//cvGoodFeaturesToTrack(src_gray, eig_image, temp_image, frame1_features, &number_of_features, .01, .01, NULL);

cvGoodFeaturesToTrack(src_gray, eig_image, temp_image, frame1_features, &number_of_features, 0.01, 5, 0, 3, 0, 0.04 );
//&number_of_features 로 추출된 점의 개수 나온다.  추출되는 점의 개수를 입력으로 제한함과 동시에 출력도...




*** 캠 입력받기

IplImage *src;       //source 이미지니까 src로 이름지음

//capture for cam
 CvCapture* capture = cvCaptureFromCAM(0);

 //get init scene
 cvGrabFrame(capture);
 src=cvRetrieveFrame(capture);

......
cvGrabFrame(capture);
src=cvRetrieveFrame(capture);
......

cvReleaseCapture( &capture );

//다른 방법
IplImage *src;
CvCapture* capture = cvCaptureFromCAM(0);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH,640);    //잘 안됨
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT,480);

...
src = cvQueryFrame( capture );.
...

// 또다른 방법 (추가)
VidFormat vidFmt = { 1600, 1200, 7.5 };     // 캠 영상의 실제 크기 및 Frame Rate
   
int nSelected = cvcamGetCamerasCount();
    if( nSelected != 0 )
    {
        CRect rtWndCam;
        int nDispWidth, nDispHeight;
  CWnd* pWndCam = GetDlgItem(IDC_STATIC_CAM);
        pWndCam->GetWindowRect(&rtWndCam);
        nDispWidth = rtWndCam.Width();
        nDispHeight = rtWndCam.Height();

        cvcamSetProperty(0, CVCAM_PROP_ENABLE, CVCAMTRUE);
  cvcamSetProperty(0, CVCAM_PROP_SETFORMAT, &vidFmt); // 미리 설정된 값으로 고정
//   
cvcamGetProperty(0, CVCAM_VIDEOFORMAT, NULL);  // 시작할때 선택 가능
       
cvcamSetProperty(0, CVCAM_PROP_RENDER, CVCAMTRUE);
        cvcamSetProperty(0, CVCAM_PROP_WINDOW, &pWndCam->m_hWnd);
        cvcamSetProperty(0, CVCAM_RNDWIDTH, &nDispWidth);
        cvcamSetProperty(0, CVCAM_RNDHEIGHT, &nDispHeight);
        cvcamSetProperty(0, CVCAM_PROP_CALLBACK, CallBackCam);

        cvcamInit();
        cvcamStart();
    }
    else
    {
        MessageBox("카메라가 연결되어 있지 않습니다.");
    }




*** Optical Flow
voidcvCalcOpticalFlowPyrLK(
    const CvArr* prev,   // 첫 번째 이미지
    const CvArr* curr,   // 두 번째 이미지
    CvArr* prev_pyr,   // 첫 번째 이미지의 피라미드
    CvArr* curr_pyr,   // 두 번째 이미지의 피라미드
    const CvPoint2D32f* prev_features,   // 첫 번째 이미지에서 원래 점의 위치
    CvPoint2D32f* curr_features,   // 두 번째 이미지에서 찾은 점의 위치
    int count,   // 찾으려는 점의 갯수
    CvSize win_size,   // 탐색 윈도우의 크기
    int level,   // 피라미드의 레벨 지정
    char* status,  // status=1:이동된 위치를 찾은 경우, status=0:이동된 위치를 찾지 못한 경우
    float* track_error,  // NULL
    CvTermCriteria criteria,   // 종료조건
    int flags);   // CV_LKFLOW_INITIAL_GUESSES 등




*** Line Fitting  (polar 코디네이트가 아니라 단점 있음)

int count = 0;        // total number of points  
float *line;     
 
CvPoint  left, right;    

//CvMat point_mat = cvMat( 1, count, CV_32SC2, mid_points );    
//cvFitLine( &point_mat, CV_DIST_L2 , 0, // line[0]:vector_x, line[1]:vector_y               
// 0.01, 0.01,  line );        // line[2]:x_n, line[3]:y_n    
//
long double a, b, c, d, e, f;
////b가 기울기, a가 절편
//b = line[1]/ line[0];       
//a = line[3]- b*line[2];       
b=((float)right.y-(float)left.y)/((float)right.x-(float)right.y);

//left.x=mid_points[0].x;
//left.y=b*left.x+a;

//right.x=mid_points[count-1].x;
//right.y=b*right.x+a;

//CvPoint center;    
//center.x = line[2];    
//center.y = line[3];     // can draw from left to right directly    
//cvLine( processed_image, center, left, CV_RGB(255,255,255), 1, 8 );    
cvLine( Draw_results, left, right, CV_RGB(255,0,0), 1, 8 );    




*** Mean-Shift Segmentation

//입출력 IplImage, spatial과 color radius 매개변수, level of scale pyramid(2 또는 3 적당)
cvPyrMeanShiftFiltering(src_color, src_result, 2, 40, 3);




*** 체스보드 마크 탐지하기

int i;
int nCornerNum = 3 * 3; // number of corners in the chessboard (3 * 3)
int MAX_COUNT = nCornerNum;   // 5000

CvSize pattern_size = cvSize( COL_CHESS_CORNER_NUM, ROW_CHESS_CORNER_NUM );

 
CvPoint2D32f *left_corners = new CvPoint2D32f[nCornerNum];
CvPoint2D32f *right_corners = new CvPoint2D32f[nCornerNum];

int iLeft_corner_count, iRight_corner_count;
 
// Get the number of left and right corners
int iFoundLeft  = cvFindChessboardCorners(pLeftImg, pattern_size, left_corners, &iLeft_corner_count, CV_CALIB_CB_ADAPTIVE_THRESH);
int iFoundRight = cvFindChessboardCorners(pRightImg, pattern_size, right_corners, &iRight_corner_count, CV_CALIB_CB_ADAPTIVE_THRESH);
//////////////////////////////////////////////////////////////////////////

//printf("\n--------------  Marker Results -----------------------------\n");
//printf("Number of Left Corners: %d\n", iLeft_corner_count);

cvDrawChessboardCorners(pLeftImg, pattern_size, left_corners, iLeft_corner_count, iFoundLeft);
cvDrawChessboardCorners(pRightImg, pattern_size, right_corners, iRight_corner_count, iFoundRight);
 /*
 for (i = 0; i < iLeft_corner_count; i++)
 {   
  DrawCorner(pLeftImg, cvPointFrom32f(left_corners[i]));
  //printf("(%d,%d)\t", cvPointFrom32f(left_corners[i]).x, cvPointFrom32f(left_corners[i]).y);
 }
 */

 //printf("\nNumber of right Corners: %d\n", iRight_corner_count);
 //for(i=0; i<iRight_corner_count; i++)
 //{
 // DrawCorner(pRightImg, cvPointFrom32f(right_corners[i]));
 // //printf("(%d,%d)\t", cvPointFrom32f(right_corners[i]).x, cvPointFrom32f(right_corners[i]).y);
 //}

float *plane = new float[4]; // return value
for (i=0; i<4; i++)    // Initialization, even though the plane equation is wrong
{
    plane[i] = 1;  
}
 
// Calculate the plane equation based on the chessboard
if( iLeft_corner_count == iRight_corner_count && iLeft_corner_count == nCornerNum) // Left Corners and right corners should be same
{
    CvPoint *leftPoints = new CvPoint[nCornerNum];
    CvPoint *rightPoints = new CvPoint[nCornerNum];
    for(i=0; i<nCornerNum; i++)
    {
        leftPoints[i] = cvPointFrom32f(left_corners[i]);
        rightPoints[i] = cvPointFrom32f(right_corners[i]);
    }
  
    plane = planeEquationfrom2DPoints(leftPoints, rightPoints, nCornerNum, baseLine, focal, u0, v0);

    // output the plane equation result
    printf("\n-------------------------  Plane Equation ------------------------\n");
    for(i=0; i<4; i++)
    {
        printf("%.4f\t", plane[i]);
    }
    printf("\n");
    //----------------------------------------------------------

    delete [] leftPoints;
    delete [] rightPoints;
}
else
    printf("No Enough Corners For Marker \n");  // should modify

//if (left_corners)
// cvFree(&left_corners);
//if (right_corners)
// cvFree(&right_corners);
 
if (left_corners)
    delete [] left_corners;
if (right_corners)
    delete [] right_corners;
return plane;




*** 히스토그램 평활화 (histogram equalization)

IplImage* Src          = cvCreateImage(cvSize(width,height), 8, 1);   //원본 이미지
IplImage* Equalized = cvCreateImage(cvSize(width,height), 8, 1);   //평활화 된 이미지

cvEqualizeHist( Src, Equalized );




*** OpenCV 외 유용한 코드들


//파일에서 불러오기
FILE *fp = fopen(".\img.txt", "r");

if(fp == NULL) 
    return false;

while (fgets(buffer,BUFFERSIZE,fp))
{
    label = strtok(buffer,ct);
    if(label == NULL)
        continue;

    pDPT[p_index*NUMOFDIMESION] =  (float)atof(label);
    pDPT[p_index*NUMOFDIMESION + 1] = (float)atof(strtok(NULL,ct));
    pDPT[p_index*NUMOFDIMESION + 2] = (float)atof(strtok(NULL,ct));

    pBGR[c_index*NUMOFDIMESION] = (unsigned char)atoi(strtok(NULL,ct));
    pBGR[c_index*NUMOFDIMESION +1] = (unsigned char)atoi(strtok(NULL,ct));
    pBGR[c_index*NUMOFDIMESION +2] = (unsigned char)atoi(strtok(NULL,ct));

    pGray[c_index] = pBGR[c_index*NUMOFDIMESION];

    strtok(NULL,ct);
    strtok(NULL,ct);
    temp = strtok(NULL,ct);

    if(atoi(&temp[1]) <= 0)
    {
        // zero disparity or invalid 3D point
        pDPT[p_index*NUMOFDIMESION] =  INVALID_DEPTH_INFO;
        pDPT[p_index*NUMOFDIMESION + 1] = INVALID_DEPTH_INFO;
        pDPT[p_index*NUMOFDIMESION + 2] = INVALID_DEPTH_INFO;
    }

 

    p_index++;
    c_index++;
}

fclose(fp);

//3D만 가져올 때
char buffer[1024];
char *label;
char ct [] = " ,\t\n";
int index=0;

FILE *fp = fopen(".\img.txt", "r");

if(fp == NULL) 
    return;

while (fgets(buffer,1024,fp))
 {
  label = strtok(buffer,ct);
  if(label == NULL)
   continue;

  p_3Dpt[index*3    ] = (float)atof(label);
  p_3Dpt[index*3 + 1] = (float)atof(strtok(NULL,ct));
  p_3Dpt[index*3 + 2] = (float)atof(strtok(NULL,ct));

  index++;

  if(index>=307200)
   break;
 }

fclose(fp);



//메모리, 용량 절약형 가져올 때
FILE *fp;
fp = fopen(file_name,"rt");

if(!fp)
{
  printf("\ncan not open 3dmfile\n");
  return false;
}

while (fgets(buffer,2000,fp))
{
  label = strtok(buffer,ct);

  if(label == NULL) continue;

  if(!strcmp("ImageWidth",label))
  {
    //m_imagewidth = atoi(strtok(NULL,ct));///samplingratio;
  }
  else if(!strcmp("ImageHeight",label))
  {
    //m_imageheight = atoi(strtok(NULL,ct));///samplingratio;
  } 
  else if(!strcmp("F",label))
  {
    double x,y;
    double x3,y3,z3;
    x  = atof(strtok(NULL,ct));
    y  = atof(strtok(NULL,ct));

    

    x3  = (double)atof(strtok(NULL,ct));
    y3  =  (double)atof(strtok(NULL,ct));
    z3  = (double)atof(strtok(NULL,ct));

    m_p3Dpt[3*(GetWidth() * (int)y + (int)x)  ] = x3;
    m_p3Dpt[3*(GetWidth() * (int)y + (int)x)+1] = y3;
    m_p3Dpt[3*(GetWidth() * (int)y + (int)x)+2] = z3;
    //y3  = -(double)atof(strtok(NULL,ct));

    // SVS ver 3.2 used mm scale
    //x3DPoints.push_back((float)x3*scale);
    //y3DPoints.push_back((float)y3*scale);
    //z3DPoints.push_back((float)z3*scale);

    // SVS ver 4.4 use m scale (model is saved by using m scale)
    //x3DPoints.push_back((float)x3);
    //y3DPoints.push_back((float)y3);
    //z3DPoints.push_back((float)z3);
    //if(idxDB == WCCup) printf("\nx=%f,\ty=%f,\tz=%f",x3,y3,z3);
  } 
}
fclose(fp);



//파일로 저장하기
FILE *fp = fopen("@@_FilterResult.txt", "at+");
fprintf(fp, "%d %f\n", nFrameNum, pEstimatedObjectPose[11]);
fclose(fp);

//메모리 카피
memcpy(src_color->imageData, m_pColorImage, sizeof(unsigned char)*width*height*3);

//3D를 2D로 그리기 (대충)
for(int i=0;i<width;++i)
{
    for(int j=0;j<height;++j)
    {
        if((m_p3Dpt[3*(i+width*j)+2]>0.5)&(m_p3Dpt[3*(i+width*j)+2]<2.0))
            view_3D->imageData[i+width*j]=((m_p3Dpt[3*(i+width*j)+2]-0.5)/1.5)*255;
        else
            view_3D->imageData[i+width*j]=0;
    }

}

 

Posted by 아몰라

'프로그래밍 기초 > 영상처리' 카테고리의 다른 글

얼굴인식의 역사, 이슈, 알고리즘, Process flow, 기본적인 기술 비교  (1) 2011.11.06
이진화하기  (0) 2011.11.02
마우스 이벤트  (0) 2011.10.31
키보드 이벤트 처리  (0) 2011.10.30
문자 출력  (1) 2011.10.30
Posted by 아몰라

출처 http://www.bluenics.com/ , OpencvKorea


Automatic Face Recognition of Behavioral or Physiological Characteristicin Human Body

Ace Recognition Speed
Face Database Size
Development face recognition system
Experiment of Face Recognition

  The 1970's : general pattern classification method
research the features in face (profiles)
  The 1980's : continuous research pattern
  The 1990's : neural network classifier
capacity of real time caculation and adaptation
  The 2000's : concentration of research pattern
xcellent face recognition systems

  Public Method : Skin color method - general method,used combination method
Eigen face method - generalized eigen face, frontal -face focusing view
Neural Networks method - adaptation well in still image,train with face image but not
Features method - flexibility image scale,viewpoint of faces
Combination method - feature base + skin color


  Face recognition
  techniques :
Principal component analysis [S.Romdhani,1997]
Local feature Analysis [P.S.Pensv,1998]
Bayesian face recognition [A.Pentland,1996]
Gabor wavelets and elastic bunch graph matching algorithm [L.Wiskott,1997]
Linear Discriminant analysis [K.Etemad,1996]

  출입관리 보안응용분야 : 출입문 통제시스템
근태관리 시스템
실시간 감시 시스템
  Tcp/Ip 서버기반 응용분야 : 얼굴인식 화상 회의 및 채팅
인터넷 사용자 인증 image bank운영
  PC 기반 응용 분야 : 개인 사용자 로그온
파일 Encription
Screen Saver
  금융분야 응용분야 : CD /ATM Face Recognition Solution
POS Face Recognition Solution
Smart card 내에 얼굴영상등록후,ATM에서 카드인증
  Enterainment 응용분야 : 대화형 얼굴인식 완구
  가상현실 분야 : 3차원 얼굴인식 캐릭터
2차원 애니메이션 캐릭터
  온라인 교육 분야 : 사용자 인증,원격 교육


얼굴을 인식하는 기술은 매우 복잡하고 변수가 많은 기술로서 이의 소프트웨어적인 개발도 최근에 이르러서야 이루어졌습니다.

먼저 카메라가 얼굴의 이미지를 잡으면 소프트웨어가 이를 템플릿(Templates)과 비교하는 것으로 얼굴인식기술은 지칭될 수 있습니다.


얼굴인식의 근간을 이루는 기술은 두 가지로 구분되어지는데 첫번째는 얼굴의 각 구성요소의 특징값과 상호관계- 예컨대 코 길이와 눈으로부터의 거리 등을 비교하는 것이고 두번째는 얼굴의 가장 중요한 이미지 데이터- 예컨대 코의 크기등- 를 데이터베이스에 저장되어 있는 얼굴의 데이터와 비교, 매칭시키는 방법입니다. 이러한 얼굴인식 기술은 여타 생체인식 기술에 비하여 다음과 같은 특징을 가지고 있습니다.


생체인식의 기본 입력테이터가 되는 생체 특성값을 카메라를 통하여 얻게 되므로 근접식 또는 접촉식 기술보다 비교적 먼 거리에서 동작될 수 있습니다. (Recognized in a distance)
인식의 속도가 비교적 빠릅니다. (Relatively high recognition speed)


다수 중에서 특정의 값을 가지는 데이터를 찾을 수 있습니다. (Enough to conduct 1 - to - many searches)
기술의 종류
얼굴의 기학적인 특징을 이용한 인식기술 (Geometrical feature analysis)
눈, 코, 입과 같은 얼굴의 특징점들의 위치나 크기 또는 이들간의 거리와 같은 기하학적 인자들만으로도 각 개개인의 얼굴을 인식할 수 있다는 사실에 착안한 것으로서 이들 기하학적 특징들은 입력화상의 해상도를 낮추었을 때 최종적으로 남는 요소들에 해당합니다. 이는 얼굴인식에서 가장 보편적으로 이용하는 방법론입니다.
Eigenface를 이용한 방법(Eigenface approach)
Eigenface란 '고유얼굴'이라는 의미를 가지는데 이는 MIT대학의 Sirovich와 Kirby에 의해 제안된 방법입니다. 사람얼굴을 저차원격으로 표현(Low - dimentional representation)할 수 있도록 하여 얼굴이미지의 기본요소를 분석(Principal components analysis)할 수 있도록 한 것인데 이 기본요소란 얼굴이미지의 변화를 나타내는 일련의 특징들을 의미하는 것으로 수학적으로 표현하면 하나의 얼굴 이미지군을 나타내는 공변(共變) 행렬(Covariance matrix)의 Eigenvector를 의미합니다. 먼저 위 기본요소들에 입력된 얼굴이미지를 투영시킨 후 이들을 저장된 얼굴이미지의 투영체와 비교하거나 상관시켜 특징들을 추출합니다. 이 추출된 특징들을 'Eigenface'또는 'Holon'이라고 하는데 이것을 가중치를 적용한 다중 템플릿 매칭방법으로 분류할 수 있는 것입니다.
템플릿 매칭을 이용한 방법(Template matching approach)
이는 얼굴이미지를 얼굴 전체를 나타내는 하나의 템플릿 화상과 비교하여 이에 따른 상관도를 분석함으로써 얼굴을 인식하는 방법론입니다.
인공신경망을 이용한 학습형 인식방법(Neural network mapping approach)
이미 여러분야에서 활용되고 있는 신경망 기술을 얼굴인식분야에 접목시킨 것으로서 통계적 분석을 기반으로 하는 신경망의 학습 및 인식기능을 이용하여 얼굴을 인식하는 방법으로 오늘날 가장 큰 비중을 차지하고 있는 방법입니다.

'프로그래밍 기초 > 영상처리' 카테고리의 다른 글

Haar분류기에 대한 정보  (0) 2011.11.16
이진화하기  (0) 2011.11.02
마우스 이벤트  (0) 2011.10.31
키보드 이벤트 처리  (0) 2011.10.30
문자 출력  (1) 2011.10.30
Posted by 아몰라

이진화란?



요즘 카메라로 사진을 찍으면 칼라로 사진을 보통 사진을 찍게 되는데

사람이 보기에는 그냥 빨간색과 검정색옷을 입고 주변 색들도 눈으로 보이는 것과 같지만...

컴퓨터는 조명이나 그림자, 잡영 등에 영향을 받아서 색이 다 다르게 보인다.

그래서 컴퓨터에게 더 쉽게 이해하기 쉬운 영상으로 만들어주는 것이 이진화이다.

검정색과(0) 흰색(255)로 컬러 값을 바꾸는 것이다.



IplImage 타입의 영상을 이진화 하기 위해 사용하는 함수는 cvThreshold라는 함수이며,
이는 입력으로 들어가는 영상의 각 채널을 이진화 한다.
이런 이유로 컬러영상(3개 채널)을 이진화 하는 경우, R, G, B 각각을 이진화 하기 때문에
아래와 같이 의도하지 않은 영상을 얻게 될 수도 있다.



그런 이유 때문에 이진화 전에는 cvCvtColor()를 이용하여 Gray로 변환 후 이진화 한다.
cvCvtColor()의 세 번 째 인수는 어떤 컬러맵으로 변환할 것인지 선택할 수 있으며,
OpenCV에서 제공하는 방법들은 CV_BGR2GRAY 뿐만 아니라 
CV_BGR2YCrCb, CV_BGR2HSV, CV_BGR2Lab 등 여러가지이며 이는 cv.h 파일에서 확인할 수 있다.


cvThreshold() 함수는 실제로 이진화를 수행하는 함수로,
세 번 째 인수는 문턱치를 설정하고,
네 번 째 인수는 문턱치를 넘어선 픽셀들을 어떤 값으로 설정할 것인지를,
다섯 번 째 인수는 이진화 알고리즘을 선택할 수 있다.

중요함수

1.

cvThreshold(const CvArr*  src, CvArr*  dst, double  threshold, double  max_value, int threshold_type)

원본영상, 이진화가 된 후 저장될 영상, 경계가 되는 수치값(임계값), 임계 값을 넘는 픽셀값을 바꿔줄 최대값 설정,이진화방식)


이진화방식

#define CV_THRESH_BINARY      0  //  임계 값 이하 : 0, 임계 값 초과 : 1
#define CV_THRESH_BINARY_INV  1  // 임계 값 이하 : 1, 임계 값 초과 : 0 
#define CV_THRESH_TRUNC       2  // 임계 값 이하는 변화 없음, 임계 값 초과는 임계 값
#define CV_THRESH_TOZERO      3  //   임계 값 이하는 0, 임계 값 초과는 그대로
#define CV_THRESH_TOZERO_INV  4  // 임계 값 이하는 그대로, 임계 값 초과는 0



2.

cvCvtColor( const CvArr* src, CvArr* dst, int code )

원본영상, 변환후 저장될 영상, Color 변환모드


Color 변환모드

CV_RGB2GRAY  - 흑백으로 변환
CV_RGB2YCrCb  -      주로 Skin Color 모델을 할 때 변환
CV_RGB2HLS  - H(Hue색상), L(Luminance,휘도),S(Saturation,채도)
CV_RGB2HSV - 모든 컬러를 Hue, Saturation, Value로 표현하는 방식
CV_RGB2Lab - L은 밝기인 명도, a 조합은 녹색에서 적색의 보색 b 조합은 황색에서 청색의 보색
CV_RGB2Luv -  CIE Yxy색표계에서 지각적 등보성을 보완한 색 공간



결과










[참고] OpenCV 강좌 04. 영상 이진화 하기 (OpenCV KOREA 대한민국 최고의 컴퓨터비젼 커뮤니티)





 

Posted by 아몰라
이전버튼 1 이전버튼