[c++] 동영상 파일에서 특정 구간 추출하기

먼저 OpenCV를 사용하여 동영상 파일을 로드하고 특정 구간의 프레임을 추출할 수 있습니다. 다음은 OpenCV를 사용하여 C++에서 동영상 파일에서 특정 구간을 추출하는 예제 코드입니다.

#include <opencv2/opencv.hpp>
#include <iostream>

int main() {
    // Open the video file
    cv::VideoCapture cap("input_video.mp4");

    if (!cap.isOpened()) {
        std::cerr << "Error opening video file" << std::endl;
        return -1;
    }

    // Set the start and end frame indices
    int start_frame = 100; // Start frame index
    int end_frame = 200;   // End frame index

    // Set the current frame index
    int frame_index = 0;

    // Iterate through the frames and extract the frames within the specified range
    while (frame_index < end_frame) {
        cv::Mat frame;
        cap >> frame;
        
        if (frame_index >= start_frame) {
            // Process the frame within the specified range
            // ...

            // Save or display the frame
            // ...
        }

        frame_index++;
    }

    // Release the video capture object
    cap.release();

    return 0;
}

또는 FFmpeg 라이브러리를 사용하여 C++에서 동영상 파일에서 특정 구간을 추출할 수도 있습니다. FFmpeg는 더욱 높은 수준의 유연성을 제공하며 다양한 비디오 및 오디오 형식을 지원합니다.

FFmpeg를 사용하여 동영상 파일에서 특정 구간을 추출하는 방법에 대한 예제 코드는 다음과 같습니다.

#include <iostream>

extern "C" {
#include <libavformat/avformat.h>
}

int main() {
    // Register all the codecs, demuxers, and protocols
    av_register_all();

    // Open the video file
    AVFormatContext* format_context = avformat_alloc_context();
    if (avformat_open_input(&format_context, "input_video.mp4", NULL, NULL) != 0) {
        std::cerr << "Error opening video file" << std::endl;
        return -1;
    }

    // Find the stream information
    if (avformat_find_stream_info(format_context, NULL) < 0) {
        std::cerr << "Error finding stream information" << std::endl;
        return -1;
    }

    // Set the start and end timestamps for the extraction
    int64_t start_time = 1000000; // Start time in microseconds
    int64_t end_time = 2000000;   // End time in microseconds

    // Iterate through the packets and extract the packets within the specified range
    AVPacket packet;
    while (av_read_frame(format_context, &packet) >= 0) {
        if (packet.pts >= start_time && packet.pts <= end_time) {
            // Process the packet within the specified range
            // ...

            // Save or write the packet
            // ...
        }

        av_packet_unref(&packet);
    }

    // Close the video file
    avformat_close_input(&format_context);
    avformat_free_context(format_context);

    return 0;
}

이러한 예제 코드를 기반으로 원하는 특정 구간의 동영상을 추출하는 데 필요한 추가적인 처리 및 출력 방법을 적용할 수 있습니다.