0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C言語】pタイル法によるPGM画像の2値化

Last updated at Posted at 2023-12-15

はじめに

C言語の学習として,グレースケール画像に対して2値化処理を行う課題が出た.
もしかしたら,同じ課題に直面する人がいるかもしれないため共有したい.

pタイル法とは

pタイル法とは, 「対象の面積が全体の面積のp%となるように閾(しきい)値を設定する」2値化方法である.

つまり,対象を真っ白として,画像を真っ白と真っ黒で構成したいならば,

$ \{ 真っ白の面積 \} : \{ 真っ黒の面積 \} = p : (100-p)$

となるような閾値を設定し,2値化処理をおこなう.

【コード】C言語でpタイル法を実現する

以下は,自分なりに作成した最終版である.

pTileMethod.cでは,pがパーセントではなく,割合になっています.
p=0.8ならば,80%となります.

pTileMethod.c
    /*
    
    .
    . 画像を読み込む処理
    .
    
    */

    
    //画像の画素は,int型2次元配列image[ySize][xSize]で参照できるものとする.
    
    double p;
    printf("p:");
    scanf("%lf", &p);

    int allData = ySize * xSize;

    int targetedArea = allData * p;

    //0~255の各値が出た回数をカウント
    int countColor[256];
    for (int i = 0; i < 256; i++)
    {
        countColor[i] = 0;
    }
    for (int y = 0; y < ySize; y++)
    {
        for (int x = 0; x < xSize; x++)
        {
            countColor[image[y][x]]++;
        }
    }

    //降順に, 出た回数の総和をとる
    int tmp = 0;
    int border;
    for (int i = 255; i >= 0; i--)
    {
        tmp += countColor[i];

        //総和が全体画素数のp割以上になったら,そこをしきい値とする.
        if (tmp >= targetedArea)
        {
            border = i;
            break;
        }
    }

    //しきい値以上かそうでないかで2値化する.
    for (int y = 0; y < ySize; ++y)
    {
        for (int x = 0; x < xSize; ++x)
        {
            if (image[y][x] <= border)
            {
                image[y][x] = 0;
            }
            else
            {
                image[y][x] = 255;
            }
        }
    }

    /*
    
    .
    . 画像を出力する処理
    .

    */

関連

画像の平滑化にも取り組みました.

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?