Multimedia Programming 02: Play with Images Departments of Digital Contents Sang Il Park
Outline OpenCV How to start Your first OpenCV code: HelloCV Basic Functions Image and Pixel Draw Lines or whatever you want Conclusion
What is OpenCV? OpenCV – 의미 : Open Source Computer Vision Library –500 여개 이상의 함수와 알고리즘들 : Computer vision Image processing ( 영상처리 ) 이외 일반적인 목적의 함수들 – 효율적이며 가볍다 (C/C++) –Absolutely free!
Who did make this? 1999 년부터 Intel 사가 개발 Available on Windows, Linux and MacOSX. 많은 회사들과 리서치 센터 등에서 폭넓게 사용 중 Home page:
OpenCV 주된 활용 분야 –Computer Human Interaction (HCI) –Object Identification –Segmentation and Recognition –Face Recognition –Gesture Recognition –Motion Tracking –Motion Understanding –And so on.
프로그램 받는 곳
OpenCV structure CXCORE basic structures and algoritms, XML support, drawing functions CV Image processing and vision algorithms HighGUI GUI, Image and Video I/O We will mostly focus on these two in this class
HelloCV: Your First OpenCV Code Loading an image and showing it
프로젝트 시작하기 Visual Studio 6.0 또는 Visual Studio.Net 시작 Make a new project –Win32 Console Application Program Compile and run it! (Ctrl + F5)
OpenCV 초기 세팅 1. 필요한 디렉토리 세팅 –Includes: "C:\Program Files\OpenCV\cv\include" "C:\Program Files\OpenCV\cxcore\include" "C:\Program Files\OpenCV\otherlibs\highgui“ –Libraries: "C:\Program Files\OpenCV\lib“ 2. 필요한 라이브러리 파일들 세팅 : –cv.lib cxcore.lib highgui.lib
1. 디렉토리 세팅 추가 파일 디렉토리 넣는 법 (tools options): "C:\Program Files\OpenCV\cv\include" "C:\Program Files\OpenCV\cxcore\include" "C:\Program Files\OpenCV\otherlibs\highgui“
1. 디렉토리 세팅 라이브러리 디렉토리 세팅 : (tools options) "C:\Program Files\OpenCV\lib“
2. 라이브러리 파일들 세팅 필요한 라이브러리 파일들 : –cv.lib cxcore.lib highgui.lib
준비 끝 ! 프로그램 소스 코드 앞에 다음을 추가하면 OpenCV 를 사용할 준비가 끝난다. –#include #include #include
HelloCV Type this: #include "stdafx.h" #include int _tmain(int argc, _TCHAR* argv[]) { IplImage * img; img = cvLoadImage("d:\\test.jpg"); cvNamedWindow("HelloCV"); cvShowImage("HelloCV", img); cvWaitKey(); cvDestroyWindow("HelloCV"); cvReleaseImage(&img); return 0; } hellocv.cpp
Error 가 발생한다면 ? dll 파일들을 복사하여 넣자 –from: C:\Program Files\OpenCV\bin 에 있는 dll 파일들 –To: 현재 프로젝트 내의 debug folder 또는 C:\Windows\system32 폴더 아래에 복사
HelloCV
#include "stdafx.h" #include int _tmain(int argc, _TCHAR* argv[]) { IplImage * img; img = cvLoadImage("d:\\test.jpg"); cvNamedWindow("HelloCV"); cvShowImage("HelloCV", img); cvWaitKey(); cvDestroyWindow("HelloCV"); cvReleaseImage(&img); return 0; } hellocv.cpp IplImage cvLoadImage cvReleaseImage cvNamedWindow cvShowImage cvDestroyWindow cvWaitKey
OpenCV 에서의 이미지란 ? IplImage 구조체 –Image 의 포멧 ( 크기, 칼라 / 흑백 등등 ) – 실제 이미지 정보 ( 각 점의 색 )
구조체 (structure) ? 하나의 물건 ( 객체 ) 가 여러 요소로 구성되어 있을 때 효율적으로 표현하기 Example) – 학생 : 이름, 학번, 주소, 전화번호,… – 성적 : 국어점수, 수학점수, 영어점수, 총점, 평균 구조체 : 관련된 정보를 그룹화하여 표현
구조체 (structure) 구조체 : 관련된 정보를 그룹화하여 표현 학생 이름 학번 주소 전화번호 구조체 이름 멤버 변수
구조체의 정의 Example) struct student { char name[30]; int number; float grade; }; struct student { char name[30]; int number; float grade; };
멤버로의 접근 구조체변수이름. 맴버변수이름 struct score { int korean; int math; }; score a; a.korean = 30; a.math = 80; struct score { int korean; int math; }; score a; a.korean = 30; a.math = 80;
Image structure ( 이미지 구조체 ) IplImage (Image Processing Library) typedef struct _IplImage { int nSize; /* size of iplImage struct */ int ID; /* image header version */ int nChannels; int alphaChannel; int depth; /* pixel depth in bits */ char colorModel[4]; char channelSeq[4]; int dataOrder; int origin; int align; /* 4- or 8-byte align */ int width; int height; struct _IplROI *roi; /* pointer to ROI if any */ struct _IplImage *maskROI; /*pointer to mask ROI if any */ void *imageId; /* use of the application */ struct _IplTileInfo *tileInfo; /* contains information on tiling*/ int imageSize; /* useful size in bytes */ char *imageData; /* pointer to aligned image */ int widthStep; /* size of aligned line in bytes */ int BorderMode[4]; /* the top, bottom, left,and right border mode */ int BorderConst[4]; /* constants for the top, bottom,left, and right border */ char *imageDataOrigin; /* ptr to full, nonaligned image */ } IplImage;
Image I/O ( 이미지 입출력 ) IplImage* cvLoadImage(image_path, colorness_flag); 파일로 부터 이미지를 읽는다. 성공할 경우 메모리가 생성되고 IplImage pointer 를 반환 실패할 경우 NULL 값을 리턴 읽으면서 이미지의 포멧을 설정할 수 있다. #define CV_LOAD_IMAGE_COLOR 1 #define CV_LOAD_IMAGE_GRAYSCALE 0 #define CV_LOAD_IMAGE_UNCHANGED -1 DEFAULT cvSaveImage(image_path, image); 이미지를 파일로 저장한다. 형식은 확장자로 부터 결정 cvReleaseImage(image_path, image); 이미지를 저장하고 있던 메모리를 해제한다. BMP, JPEG, PNG, TIFF, PPM/PGM 포멧등이 지원됨
Image I/O ( 이미지 입출력 ) 이미지의 포멧을 바꾸어 저장하기 예 : IplImage* img = cvLoadImage(“picture.jpg”); if( img ) cvSaveImage( “picture.bmp”, img );
Windows cvNamedWindow(window_name); 윈도우를 생성한다. 윈도우는 이름을 부여할 수 있고, 각 이름을 기준으로 구분한다. cvNamedWindow(“ViewA”); cvMoveWindow(“ViewA”,300,100); cvDestroyWindow(“ViewA”); … cvShowImage(window_name, IplImage *); 주어진 이름에 해당하는 윈도우에 이미지를 보여준다. 한 이미지만을 보여 줄 수 있으며, 부분 적인 출력은 하지 못한다. cvDestroyWindow(window_name); 주어진 이름에 해당하는 윈도우를 없앤다.
User Input int cvWaitKey( int delay=0 ) 사용자가 키를 누르기를 정해진 대기시간 만큼 기다린다. 대기시간이 초과되면 다음 명령을 수행한다. 대기시간으로 0 을 설정하면 영원히 기다린다. – 시간의 값은 millisecond 대기시간을 이용하면 애니메이션을 만들 수 있 다. 활용예 ) 두 개 이상의 그림을 교대로 보여줌
What else HighGUI can do? “Smart” windows Image I/O, rendering Processing keyboard and other events, timeouts Trackbars Mouse callbacks Video I/O
Image and Pixel
픽셀 (Pixel: Picture Element) 이미지 : 픽셀의 집합 비트맵 (Bitmap)
픽셀 픽셀의 색 : 적색 (Red), 녹색 (Green), 청색 (Blue) 컬러의 수 픽셀 당 비트 수 ( 밝기 레벨 )
Pixel 의 값 = ( 위치, 색 ) 위치 : 각 픽셀의 2D 좌표 (Image Coordinate System) 색 : CvScalar ( 색을 저장하는 구조체 ) x y (0,0)(8,2)
색을 저장하는 변수 : CvScalar 4 개 이하의 숫자를 저장할 수 있도록 만든 구조체 0 번은 blue, 1 번은 green, 2 번은 red 값을 저장 Example) CvScalar s; s.val[0] = 200;(Blue) s.val[1] = 11;(Green) s.val[2] = 123;(Red) struct CvScalar { double val[4]; };
이미지에서 Pixel 값으로의 접근 CvScalar cvGet2D (IplImage*, y, x) (x,y) 에서의 칼라 값 얻기. –Example)CvScalar s; s = cvGet2D(img, 30, 40); void cvSet2D (IplImage*, y, x, CvScalar) (x,y) 에서의 칼라 값 변경 –Example)CvScalar s = cvScalar(100,0,0); cvSet2D(img, 30, 40, s); 또는 cvSet2D(img, 30, 40, cvScalar(100,0,0));
빈 이미지 생성하기 IplImage* cvCreateImage( CvSize size, int depth, int channels ); – 만들 빈 이미지의 크기, 허용 색상수를 설정하여 생성 – 컬러수 :color depth: IPL_DEPTH_8U ( 각 채널당 8bit) channels: 1,2,3,4 (1=grey, 3=color) –Example) IplImage * img; img = cvCreateImage(cvSize(200,100), IPL_DEPTH_8U,3); cvSet(image, CvScalar) – 이미지를 주어진 색으로 가득 칠한다 –Example) cvSet(img, CV_RGB(255,255,255));
So far what you’ve learned: IplImage cvLoadImage (file_name) cvCreateImage (size, depth, channels) cvSaveImage (file_name, image) cvReleaseImage (image) cvNamedWindow (window_name) cvShowImage (window_name, image) cvDestroyWindow (window_name) cvWaitKey (delay) cvGet2D (image, y, x) cvSet2D (image, y, x, cvScalar)
Put everything together! int _tmain(int argc, _TCHAR* argv[]) { IplImage * img; img = cvLoadImage("d:\\test.jpg"); cvNamedWindow("HelloCV"); cvShowImage("HelloCV", img); cvWaitKey(); int x,y; for(x=0; x<100; x++) for(y=0; y<100; y++) { CvScalar s = cvGet2D(img, y,x); s.val[0] +=50; s.val[1] +=50; s.val[2] +=50; cvSet2D(img,y,x,s); } cvShowImage("HelloCV", img); cvWaitKey(); cvDestroyWindow("HelloCV"); cvReleaseImage(&img); return 0; } HelloCV2.cpp
Coding Practice: Line Drawing Make your own function for Horizontal line drawing: – 예 ) void DrawHLine (IplImage * img, int y, int st, int ed, CvScalar color) image
Do more! Design a function that draws a rectangle – 예 ) void DrawRectangle (IplImage * img, int x, int y, int w, int h, CvScalar color) –Don’t forget to make sure a pixel is inside the image 0 width 0 height If done, try to draw 50 random boxes with random colors! (x,y) w h
For those who want more OpenCV Wiki-pages: For HighGUI: – For cxcore: – Supplied documentation: OpenCV/docs/index.htm, faq.htm A Korean Community: