3
1

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 5 years have passed since last update.

画像処理100本ノックC言語で挑戦してみる #1

Posted at

Q.1. チャネル入れ替え

画像を読み込み、RGBをBGRの順に入れ替えよ。

入力 出力
imori.jpg answer_1.jpg

回答

ピクセルの値を入れ替える部分のコードです

ex1.c
int array = 0;
for(int i = 0; i < height; i++){
    for(int j = 0; j < width*3-2; j = j+3){
        array = image[i][j+2];
        image[i][j+2] = image[i][j];
        image[i][j] = array;
    }
}

解説

RGBの3つの値はそれぞれ2次元配列に格納されていて、3つが横並びになっています。
今回はRGBをBGRの順に入れ替えるので、3つのうち頭とお尻の値を入れ替えれば良いわけです。
したがって、まずは3つ目の値(Bの値)を新しく用意した変数arrayに避難させておいて、1つ目の値(Rの値)で上書きします。この操作でRGBがRGRとなっています。
次に避難させておいたBの値を1つ目の値に上書きします。この操作でRGRがBGRとなりました。

2重ループを回していますが、入れ替えは3つ1組で行いますので、内側のfor文の変化式は2つ飛ばしになっています。

完成したプログラム(全文)

ex1.c
# include <stdio.h>
# define N 256

int main(void) {
    FILE *infp;
    FILE *outfp;
    char magic[64];
    char str[256];
    int width;
    int height;
    int max;
    char readline[N] = {'\0'};

    infp = fopen("../imori.ppm", "r");
    
    //magic
    fgets(magic, N, infp);
    //width, height
    int num[4];
    for(int i = 0; i < 2; i ++){
        fscanf(infp, "%d", &num[i]);
    }
    width = num[0];
    height = num[1];
    //max
    fscanf(infp, "%d", &max);
    //image
    int image[height][width*3];
    for(int i = 0; i < height; i ++){
        for(int j = 0; j < width*3; j ++){
            fscanf(infp, "%d", &image[i][j]);
        }
    }

    outfp = fopen("imori.ppm", "w");

    fprintf(outfp, "%s", magic);
    fprintf(outfp, "%d ", width);
    fprintf(outfp, "%d\n", height);
    fprintf(outfp, "%d\n", max);

    int array = 0;
    for(int i = 0; i < height; i++){
        for(int j = 0; j < width*3-2; j = j+3){
            array = image[i][j+2];
            image[i][j+2] = image[i][j];
            image[i][j] = array;
        }
    }

    for(int i = 0; i < height; i ++){
        for(int j = 0; j < width*3; j ++){
            fprintf(outfp, "%d ", image[i][j]);
        }
        fprintf(outfp, "\n");
    }
    return 0;
}

リンク

画像処理100本ノックを作ったった
画像処理100本ノックC言語で挑戦してみる イントロダクション

3
1
0

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?