M.S. Student at Korea Univ.
TODAY 13 TOTAL 27,553
OpenCV 2.4 다운로드부터 이미지, 비디오를 파일로 쓰기까지
지난 시간에 이어 OpenCV Tutorial을 따라가며 기억할 만한 내용들을 메모하고 있다.
연습한 코드들을 깃헙에도 커밋중이니 참고하시라

연습한 코드 보기 : https://github.com/fromme0528/OpenCV-study

OpenCV Enviroment Setting

OpenCV를 다운받고, 환경 변수 설정과 Visual Studio 설정이 필요하다.

환경변수 설정
일단 3.4.0 / VS2015로 하는것은 보류하기로 했다.
나중에 상위 버전에서 제공하는 기능이 필요하면 바꿔보기로 하자.
(그 때 쓸 참고 사이트 http://webnautes.tistory.com/912)

일단 튜토리얼에서 사용했던 OpenCV 2.4.13 / VS2012로 일단 선택하고 환경변수/시스템 설정 처리했다.

OpenCV 폴더에 있는 vc가 visual studio 버전을 의미한다고 보면 되는데 여기서 실수가 있었다.
vc14를 받고서는 visual studio 12로 작업하려고..;

또 x32 x64가 꼬여 에러가 났었는데 VS 구성 관리자에서 x64를 추가하여 동작시켰다.

Basic of OpenCV API

  • CV_8U (8 bit unsigned integer)
  • CV_8S (8 bit signed integer)
  • CV_16U (16 bit unsigned integer)
  • CV_16S (16 bit signed integer)
  • CV_32S (32 bit signed integer)
  • CV_32F (32 bit floating point number)
  • CV_64F (64 bit float floating point number)

따위의 자료구조들이 있었는데, 실제로 쓰면서 알아가고 검색하면서 배우기로.

Read & Display Image

- highgui.hpp 내부에 이미 core include하고 있음

- highgui의 두 번재 인자 flag

  • flags - There are four possible inputs
    • CV_LOAD_IMAGE_UNCHANGED - image-depth=8 bits per pixel in each channel,  no. of channels=unchanged 
    • CV_LOAD_IMAGE_GRAYSCALE - image depth=8 bits,  no. of channels=1
    • CV_LOAD_IMAGE_COLOR - image-depth=?,  no. of channels=3
    • CV_LOAD_IMAGE_ANYDEPTH - image-depth=unchanged ,  no. of channels=?
    • CV_LOAD_IMAGE_ANYCOLOR - image-depth=?,  no. of channels=unchanged 

>> depth와 channel에 대한 개념이 필요했다. 아래 설명을 보자.

To understand image-depth and concept of channels, you should be familiar with theory of image processing. So, let's discuss little bit of theory of image processing.

Any digital image consists of pixels. Any pixel should have some value. The minimum value for a pixel is 0 and it represents black.When the value of the pixel is increased, the intensity of that pixel is also increased.  In a computer memory, ). In decimal, it is 255. fixed number of bits are allocated for every pixel. Say the number of allocated bits per pixel is 8. Then the maximum number that a pixel can have is 255 (11111111 in binary)

Now what is image-depth? The image-depth means the number of bits allocated for each pixel. If it is 8, each pixel can have a value between 0 and 255. If it is 4, each pixel can have a value between 0 to 15 (1111 in binary). 

Here is a simple model of a image with image-depth of 8 bits. Each small box represents a pixel. So, each box may contain a value between 0 to 255.

Here is some properties of the following image.
    •  Image-depth 8 bit
    • 1 channel ( So, this is a grayscale image )
    • The height is 4 pixel 
    • The width is 5 pixels
    • The resolution of this image is 4x5.
This is a grayscale image (black and white image) because this image has no color content. If the value of this pixel is higher, it will be shown more brighter. If the value is low, it will be shown more darker.

Grayscale Image with image depth of 8

Following image is a simple model of a color image. Color image should consist of at least 3 planes; Red, Green and Blue. Any color can be created using a particular combination of these 3 colors. Any pixel is a combination of three 3 values. (255, 0, 0) represent pure red. (0, 255, 0) represent pure green. (255, 0, 255) represents pure violate. In the same way, you can create many color. Image-depth is 24 because each pixel is represented with 8 x 3 bits (8 bits from each channel).

Here is some properties of the following image.
    •  Image-depth 24 bit
    • 3 channels ( So, this is a color image )
    • The height is 4 pixel 
    • The width is 5 pixels
    • The resolution of this image is 4x5.

R, G, B planes of a color image

In the above model, top left pixel is (23, 231, 46). It will be shown as a greenish color because the green value(231) of that pixel is larger than the red(23) and blue(46) value.


       Mat img(500, 1000, CV_8UC3,Scalar(0,0,100)); //B,G,R

Scalar => 순서가 B,G,R이었다.

Capture Video From file


The destructor of this class will deallocated any associated memory with this object. Therefore you don't need to deallocate memory explicitly in your program.
  • VideoCapture::~VideoCapture()
Destructor of VideoCapture object will destroy any associated memory of that particular object. This destructor will be called implicitly on exit of the main method of the above program.

  • waitKey(30)
The function waits for 30 milliseconds. If a key was pressed before the specified time, it returns the ASCII value of the pressed key. If that value is 27 (ASCII value of 'esc' key is 27), the program will execute inside the if block. If no key is pressed during that 30ms, the function returns -1 program will continue the while loop.


At first, this program captures a video from a file. Then the program enters into a infinite loop. In that loop, it grabs frames from the captured video sequentially, decodes it, shows it in a window and waits for 30 milliseconds. If the video file has no more frames or if the user presses the 'esc' key, the program will break the infinite loop.

Using waitKey(int) function is very important because imshow(string&, MAT) function need time to paint the image in the window and waitKey(int) will give that necessary time.


연결된 카메라가 없어서 테스트하지 못해봄...

Write Image & Video to File



C의 형변환의 위험성을 보완하여 C++은 여러가지 캐스팅 오퍼레이터를 제공함.


static의 경우는 컴파일 타임에 체크한다는 특징이 있음.
자세한 것은 아래 페이지 참조

  • VideoWriter::VideoWriter(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
This is the constructor of the VideoWriter class. It initializes the object with following parameters
    • const string& filename - Specify the name and the location of the output file. The video stream is written into this file
    • int fourcc - specify the 4 character code for the codec which is used to compress the video. Your computer may not be supported some codecs. So, if you fail to save the video, please try other codecs. Here are some popular codecs.
      • CV_FOURCC('D', 'I', 'V', '3') for DivX MPEG-4 codec
      • CV_FOURCC('M', 'P', '4', '2') for MPEG-4 codec
      • CV_FOURCC('D', 'I', 'V', 'X') for DivX codec 
      • CV_FOURCC('P','I','M','1') for MPEG-1 codec
      • CV_FOURCC('I', '2', '6', '3') for ITU H.263 codec
      • CV_FOURCC('M', 'P', 'E', 'G') for MPEG-1 codec

For Windows users, it is possible to use -1 instead of the above codecs in order to choose compression method and additional compression parameters from a dialog box. It is a best method for Microsoft Windows users.

    • double fps - frames per seconds of the video stream. I have used 20. You can try different values. But the codec should support the fps value. So, use an appropriate value.
    • Size frameSize - Size object which specify the width and the height of each frame of the video stream.
    • bool isColor - If you want to save a color video, pass the value as true. Otherwise false. Remember codec should support whatever value, you pass. In the above example, you have to give true as the 5th argument. Otherwise it will not work.

  Comments,   0  Trackbacks
댓글 쓰기
최근 작성 댓글
최근 작성 트랙백
글 보관함
«   2019/03   »
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30