『OpenCVによる画像処理入門』練習問題4.2


『OpenCVによる画像処理入門』の練習問題4.2をやった。

練習問題4.2

1

2次元配列imageを使用してPGM画像を作成する。

※main関数に毎回サンプルプログラムを書いていくと長大になりすぎるため、
subX()の関数を作り、適宜mainから呼ぶような構成にした。

プログラム

sub6_1.cpp
#include "sub.h";

using namespace std;

int sub6()
{
    const int width = 9, height = 9;
    unsigned char image[height][width];

    string filename = "output.pgm";
    ofstream fout(filename);

    for (int y = 0;y < height;y++)
    {
        for (int x = 0;x < width;x++)
        {
            /* ここから作成開始 */
            int tmp = 32 * x + 32 * y;

            if (tmp < 256)
            {
                image[x][y] = tmp;
            }
            else if (tmp == 256)
            {
                image[x][y] = 255;
            }
            else if (tmp > 256)
            {
                image[x][y] = 256 - (tmp - 256);
            }
            /* ここまで */
        }
    }

    fout << "P2" << endl;
    fout << width << " " << height << endl;
    fout << "255" << endl;
    for (int y = 0;y < height;y++)
    {
        for (int x = 0;x < width;x++)
        {
            fout << (int)image[x][y] << " ";
        }
        fout << endl;
    }
    fout.flush();
    fout.close();

    return 0;

}

作成ファイル

output.pgm
P2
9 9
255
0 32 64 96 128 160 192 224 255 
32 64 96 128 160 192 224 255 224 
64 96 128 160 192 224 255 224 192 
96 128 160 192 224 255 224 192 160 
128 160 192 224 255 224 192 160 128 
160 192 224 255 224 192 160 128 96 
192 224 255 224 192 160 128 96 64 
224 255 224 192 160 128 96 64 32 
255 224 192 160 128 96 64 32 0 

表示

2

1と同じ画像を、1次元配列imageを使用して作成する。

プログラム

sub6_2.cpp
#include "sub.h";
using namespace std;

int sub6()
{
    const int width = 9, height = 9;
    unsigned char image[height * width];

    string filename = "output.pgm";
    ofstream fout(filename);

    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            /* ここから作成開始 */
            int tmp = 32 * x + 32 * y;

            if (tmp < 256)
            {
                image[y*width+x] = tmp;
            }
            else if (tmp == 256)
            {
                image[y * width + x] = 255;
            }
            else if (tmp > 256)
            {
                image[y * width + x] = 256 - (tmp - 256);
            }
            /* ここまで */
        }
    }

    fout << "P2" << endl;
    fout << width << " " << height << endl;
    fout << "255" << endl;
    for (int y = 0;y < height;y++)
    {
        for (int x = 0;x < width;x++)
        {
            fout << (int)image[y*width + x] << " ";
        }
        fout << endl;
    }
    fout.flush();
    fout.close();

    return 0;

}

pgmファイルおよび画像は1と同じなので省略。