かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

OpenCVで輪郭抽出と、最大の領域を求める方法

超、自分用メモ。

cv::Mat src = cv::imread("streat2.jpg", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat input(src.rows, src.cols, src.type());

// 2値化
cv::threshold(src, input, 200, 255, CV_THRESH_BINARY);

// 輪郭を抽出
std::vector<std::vector<cv::Point>> contours;
cv::findContours(input, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);

// 最大面積の領域をピックアップ
auto maxContour = std::max_element(contours.begin(), contours.end(), [](std::vector<cv::Point> x, std::vector<cv::Point> y) {
    return cv::contourArea(x) < cv::contourArea(y);
});

// cv::RotatedRectに変換
auto area = [maxContour](){
    cv::Mat pointf;
    cv::Mat(*maxContour).convertTo(pointf, CV_32F);
    return cv::fitEllipse(pointf);
}();

// 描画
cv::ellipse(src, area, cv::Scalar(255, 0, 0), 2);

C++のラムダ式はじめて使ったけど便利ですね。STLと相性いいです。