[英]Getting the 0-255 values from a pixel in a ppm file C
好的,所以我有代碼將從ppm圖像中讀取標題,為圖像的大小分配內存,並將為每個像素成功打印空白點(在終端中重復的隨機數)。 我需要知道的是如何讀取每個像素的紅色綠色和藍色值(3個獨立的值,范圍從0-255)。 我不知道如何在每個像素內訪問此數據。 到目前為止,這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
int subscript(int row,int column,int numberColumns);
int sub(int rd, int gr, int bl);
//table of contents for the subscript
int main(void){
char header[5];
scanf("%s",header);
printf("%s",header);
printf("\n");
int width, height, depth;
scanf("%d %d %d\n", &width, &height, &depth);
printf("%d %d %d\n", width, height, depth);
int red = 0;
int green = 0;
int blue = 0;
int sm;
int r = 0;
int c = 0;
//allocate memory for bit to be used throughout main
unsigned char *bit = malloc(width*height);
int *rgb = malloc(3*depth);
//loops to read in table and print it
while(r < height){
while(c < width)
{
int col;
scanf("%d",&col);
//brings in allocated memory and values
bit[subscript(r,c,width)] = col;
int clr;
rgb[sub(red,green,blue)] = clr;
int color = clr + col;
printf(" %d",clr);
c=c+1;
}
printf("\n");
r = r + 1;
c = 0;
}
free(bit);
}
int subscript(int row,int column, int numberColumns)
{
return row * numberColumns + column;
//retuns items for subscript
}
int sub(int rd, int gr, int bl)
{
return rd+gr+bl;
}
如果標題中的最大顏色值字段小於256,則PPM文件將顏色存儲為字節的三倍(每個字節分別用於r,g和b),如果顏色小於256,則存儲為兩個字節的三倍(如果大於或等於256,則為兩個字節) r,g和b中的每一個的字節數,也按該順序)。
在每通道兩個字節的情況下,字節是MSB優先(大端)。
scanf("%c", &byte_var);
會將您讀取的單個字符(字節)讀入byte_var
,這應該是適當的類型。 然后,您可以對其進行相應處理。 scanf("%hhu", &byte_var);
如果使用的是C99,它將讀取一個無符號字符-如果使用的是C89,則應查找getchar
。
現在, scanf
返回成功轉換的參數或EOF的數量,因此您應該檢查錯誤輸入和輸入結束的結果。 例如:
int n;
char c;
while ((n = scanf("%c", &c)) != EOF && 1 == n) {
// do something
}
一個示例用法是:
// Read width, height, work out how many bytes you need per pixel.
...
// Now read some pixels
// Here I assume one byte per pixel; this would be a good situation
// to use a function for reading different channel widths
w = 0, h = 0;
while ((n = scanf("%hhu%hhu%hhu", &r, &g, &b)) != EOF && 3 == n
&& w < width && h < height) {
// now do something with r, g, b
// e.g. store them in an appropriate pixels array at pixels[w][h]
...
++w;
if (w == width) {
w = 0, ++h;
}
}
我還看到您正在從stdin
中讀取內容,由於標題表明您正在使用文件,因此我發現它有點不尋常。 您可以使用fopen
打開文件(不要忘記檢查結果),使用fscanf
讀取文件,然后使用fclose
將其關閉。
但是,我建議將整個文件讀入內存並在那里進行處理,因為一次讀取幾個字節的文件速度很慢。
最后,我注意到您僅在需要bytes_per_channel
* num_channels
* width
* height
時才為bit
分配width
* height
字節,而不檢查malloc
是否失敗,也不釋放rgb
。 您應該修復這些問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.