Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
Archives
Today
Total
관리 메뉴

:)

카메라와 동영상 처리 본문

컴퓨터비전

카메라와 동영상 처리

mihee 2022. 3. 17. 18:23

카메라와 동영상 처리

카메라 열기

VideoCapture::VideoCapture(int index, int apiPreference = CAP_ANY);
bool VideoCapture::open(int index, int apiPreference = CAP_ANY);
  • index : 사용할 캡쳐 장치의 ID. 시스템 기본 카메라를 기본 방법으로 열려면 0을 지정. 여러 대의 카메라가 연결되어 있으면 0,1, ... 순서
  • apiPreference : 선호하는 카메라 처리 방법을 지정
    ex) CAP_DSHOW, CAP_MSMF, CAP_V4L
  • 반환값: VideoCapture 생성자는 VideoCapture 객체를 반환. open() 함수는 성공하면 true, 실패하면 false 반환

동영상 파일 열기

VideoCapture::VideoCapture(const String& filename, int apiPrefernce = CAP_ANY);
bool VideoCapture::open(const String& filename, int apiPreference = CAP_ANY);
  • filename : 동영상 파일 이름, 정지 영상 시퀀스, 비디오 스트림 URL 등
  • apiPreference : 선호하는 동영상 처리 방법을 지정
  • 반환값: VideoCapture 생성자는 VideoCapture 객체를 반환. open() 함수는 성공하면 true, 실패하면 false 반환

현재 프레임 받아오기

bool VideoCapture::read(OutputArray image);
VideoCapture& VideoCapture::operator >> (Mat& image);
  • image : 현재 프레임. 만약 현재 프레임을 받아오지 못하면 비어 있는 영상으로 설정됨.
  • 반환값 : VideoCapture::read() 함수는 작업이 성공하면 true, 실패하면 false 반환
  • 연산자 오버로딩은 내부에서 read() 함수를 재호출하는 wrapper 함수. read 함수를 호출하나 >> 연산자를 사용하나 동일함.

카메라와 동영상 처리하기

int main() {
    VideoCapture cpa;    // 객체 생성 후 0번 카메라 열기. == VideoCapture cap(0);, if 비디오 -> cap.open("sample.mp4");
    cap.open(0);

    if(!cap.isOpened())
        return -1;

    Mat frame, edge;
    while(true) {
        cap >> frame;    // VideoCapture 객체로부터 한 프레임을 받아 frame 변수에 저장

        if(frame.empty()) break;

        Canny(frame, edge, 50, 150);    // 받아온 프레임 처리 및 화면 출력
        imshow("frame", frame);
        imshow("edge", edge);

        if(waitKey(10) >= 0)    //일정 시간(10ms) 기다린 후 다음 프레임을 처리.
            break;
    }
}

동영상 저장

VideoWriter(const String& filename, int fourcc, double fps, Size frameSize, bool isColor = true);
bool VideoWriter::open(const String& filename, int fourcc, double fps, Size frameSize, bool isColor = true);
  • 일련의 정지 영상을 동영상 파일로 저장할 수 있는 VideoWriter 제공
  • fourcc : 압축 방식을 나타내는 4개의 문자

카메라 입력을 동영상 파일로 저장하는 예제 코드

int main() {
    VideoCapture cap(0);

    int fourcc = VideoWriter::fourcc('X', 'V', 'I', 'D');
    double fps = 15;
    Size sz = Size((int)cap.get(CAP_PROP_FRAME_WIDTH), (int)cap.get(CAP_PROP_FRAME_HEIGHT));

    VideoWriter outputVideo("output.avi", fourcc, fps, sz);

    int delay = cvRound(1000 / fps);
    Mat frame;
    while (true) {
        cap >> frame;

        outputVideo << frame;
        imshow("frame", frame);

        if (waitKey(delay) == 27)
            break;
    }


}
Comments