OpenCVについてのメモ [Memo #004]

Table of Contents

画像処理にはよくOpenCVが利用される

OpenCVとは


OpenCV(Open Source Computer Vision Library)

オープンソースのコンピュータビジョンと機械学習のソフトウェアライブラリ

リアルタイムの画像処理に使用される

画像処理と解析:画像のフィルタリング、変形、オブジェクトの検出などの基本的な機能
顔認識とオブジェクト識別:顔の検出、物体の識別や追跡など
マシンビジョンアプリケーション:3Dモデルの構築、ステレオビジョンを用いた奥行き知覚、モーショントラッキング
機械学習:k-最近傍アルゴリズム、サポートベクターマシン、人工ニューラルネットワークなどのアルゴリズムをサポート
ビデオ分析:ビデオのキャプチャ、ビデオファイルからのフレームの抽出、背景差分法など

OpenCVをVisual Studio2022で利用する

以下のサイトを参考にOpenCVをダウンロード&インストールし、Visual Studio2022のプロジェクトを設定する

https://qiita.com/h-adachi/items/aad3401b8900438b2acd

簡単な2値化処理

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

int main(int argc, char** argv) {
    // 引数チェック
    if(argc != 3) {
        std::cout << "Usage: " << argv[0] << " <input_image_path> <output_directory>" << std::endl;
        return -1;
    }

    // 画像をカラーで読み込む
    cv::Mat src = cv::imread(argv[1], cv::IMREAD_COLOR);
    if(src.empty()) {
        std::cerr << "Error: Could not open or find the image!" << std::endl;
        return -1;
    }

    // グレースケール変換
    cv::Mat gray(src.rows, src.cols, CV_8UC1);
    for(int y = 0; y < src.rows; y++) {
        for(int x = 0; x < src.cols; x++) {
            cv::Vec3b pixel = src.at<cv::Vec3b>(y, x);
            uchar grayscale = static_cast<uchar>(0.3 * pixel[2] + 0.59 * pixel[1] + 0.11 * pixel[0]); // RGB to Grayscale
            gray.at<uchar>(y, x) = grayscale;
        }
    }

    // 単純2値化
    cv::Mat dst = gray.clone();
    const uchar threshold = 128; // 閾値
    for(int y = 0; y < gray.rows; y++) {
        for(int x = 0; x < gray.cols; x++) {
            dst.at<uchar>(y, x) = (gray.at<uchar>(y, x) >= threshold) ? 255 : 0;
        }
    }

    // 画像を保存するパスを生成
    std::string inputFileName = std::string(argv[1]);
    size_t lastSlash = inputFileName.find_last_of("/\\");
    std::string outputFilePath = std::string(argv[2]) + "/" + (lastSlash != std::string::npos ? inputFileName.substr(lastSlash + 1) : inputFileName);

    // 画像を保存
    if(!cv::imwrite(outputFilePath, dst)) {
        std::cerr << "Error: Could not save the image to " << outputFilePath << std::endl;
        return -1;
    }

    std::cout << "Processed image saved to " << outputFilePath << std::endl;
    return 0;
}