2値画像の領域を違う色で塗り分ける

概要

二値画像から輪郭を検出し、連結成分ごとに異なるランダムな色で塗り分けて表示するプログラムである。

目次

関連する外部ページ

サイト内の関連情報

ソースコード

OpenCV の公式サンプルをもとにしたプログラムである。コマンドライン引数の1番目に、二値画像(白黒画像)のファイル名を与えて実行する。以下の内容で drawcontours.cpp という名前のファイルを作成する。

#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    // コマンドライン引数の 1 番目に 2 値画像(白黒)
    // のファイル名を与えてください.
    if (argc != 2)
        return -1;

    Mat src = imread(argv[1], IMREAD_GRAYSCALE);
    if (src.empty())
        return -1;

    Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);

    src = src > 1;
    imshow("Source", src);

    vector > contours;
    vector hierarchy;

    findContours(src, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);

    // トップレベルにあるすべての輪郭を横断し,
    // 各連結成分をランダムな色で描きます.
    RNG rng(12345);
    for (int idx = 0; idx >= 0; idx = hierarchy[idx][0])
    {
        Scalar color(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
        drawContours(dst, contours, idx, color, FILLED, LINE_8, hierarchy);
    }

    imshow("Components", dst);
    waitKey(0);

    return 0;
}

コンパイル方法

以下のコマンドでコンパイルする。ソースファイル名は drawcontours.cpp とする。pkg-config でOpenCVのインクルードパスとライブラリを解決する。

g++ -std=c++17 -o a.out drawcontours.cpp $(pkg-config --cflags --libs opencv4)