Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@HirosuguTakeshita

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

More than 1 year has passed since last update.

# Q.2. グレースケール化

Y = 0.2126 R + 0.7152 G + 0.0722 B

# 回答

グレースケール化する部分のコードです。

ex2.c
``````double image_gry[height][width];
int k = 0;
for(int i = 0; i < height; i ++){
for(int j = 0; j < width*3-2; j = j+3){
image[i][j] = image[i][j] * 0.2126;
image[i][j+1] = image[i][j+1] * 0.7152;
image[i][j+2] = image[i][j+2] * 0.0722;
image_gry[i][k] = image[i][j] + image[i][j+1] + image[i][j+2];
fprintf(outfp, "%d ", (int)image_gry[i][k]);
k ++;
}
fprintf(outfp, "\n");
}
``````

# 解説

まず、新たにheight × widthサイズの二次元配列を用意し、R、G、Bそれぞれの値に計算式中の係数を掛け合わせてその和を格納しました。

# 完成したプログラム（全文）

ex2.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;

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
double image[height][width*3];
for(int i = 0; i < height; i ++){
for(int j = 0; j < width*3; j ++){
fscanf(infp, "%lf", &image[i][j]);
}
}

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

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

double image_gry[height][width];
int k = 0;
for(int i = 0; i < height; i ++){
for(int j = 0; j < width*3-2; j = j+3){
image[i][j] = image[i][j] * 0.2126;
image[i][j+1] = image[i][j+1] * 0.7152;
image[i][j+2] = image[i][j+2] * 0.0722;
image_gry[i][k] = image[i][j] + image[i][j+1] + image[i][j+2];
fprintf(outfp, "%d ", (int)image_gry[i][k]);
k ++;
}
fprintf(outfp, "\n");
}

return 0;
}
``````

# リンク

0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
WEBと画像処理（超解像）