这个问题对于使用纯 C 进行图像处理有更多的理解是具有挑战性的。我已经做了一个简单的程序,使用用 GCC 编译的 C 来读取非二进制 PGM 文件。现在,当我尝试读取二进制 PGM 文件时,它已成为一个问题。可以通过使用IrvanView将JPG转换为PGM来获取此二进制 PGM 文件。
注意:请不要使用任何图像处理库(例如:OpenCV)回答。
我目前的代码是:
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 1024
#define HEIGHT 768
#define READ_IMAGE_NAME "MY_PGM_FILE_NAME.pgm"
void print_histogram_table(int *histog);
main() {
FILE *fp;
int i,j, height= HEIGHT, width=WIDTH;
char line[100];
// Color depth is 255.
unsigned char pixel_value;
fp = fopen(READ_IMAGE_NAME,"r");
// get the first four lines.
fgets (line,100,fp);
fgets (line,100,fp);
fgets (line,100,fp);
fgets (line,100,fp);
// Histogram helper
int histo[65536];
int x;
for ( x =0; x < 65536; x++) {
histo[x] = 0;
}
for(j=0;j<height;j++) {
for(i=0;i<width;i++) {
fread(&pixel_value, sizeof(unsigned char), 1, fp);
// Turn on the code below, if you want to check color on specific row and column.
// printf("row num. %d column num. %d pixel value=%d\n",j,i,pixel_value);
histo[pixel_value]++;
}
}
// Make histogram
print_histogram_table(histo);
fclose(fp);
getch();
}
void print_histogram_table(int *histog)
{
int x;
for (x= 0; x < 255; x++) {
if ( histog[x] != 0)
printf("Color number %d count %d\n", x, histog[x]);
}
}
我已经阅读了一些与我的问题相关的页面 [如何阅读 .PGM 格式文件?] ,但我找不到任何明确而简单的答案。对于我的代码中的任何错误,我深表歉意。任何关于我的代码的建议和批评都将不胜感激。
我上面的脚本无法显示正确的颜色直方图,因为如果你理性思考,你可能会得到高于 100 的像素颜色(不仅低于 100)。所以,主要问题是如何解决这个问题?
编辑我
- 添加 PGM 图像。PGM 图像样本
- 添加创建图像直方图的功能。
编辑二
- 再添加一个fget,参见示例图像。