c-试图建立一个函数来计算图像中的唯一像素



。。这是有用的东西。然而我在网上看不到任何相关信息。。这似乎有点问题。这就是为什么。。我试着自己构建这个功能:

typedef unsigned char byte;
typedef unsigned short word;
typedef unsigned long dword;
typedef struct
{
    byte R;
    byte G;
    byte B;
} RGB;
dword
getpixels
(char *FILE_NAME)
{
    dword WIDTH = 500; // example dimension
    dword HEIGHT = 500; // example dimension
    FILE* fp = fopen(FILE_NAME, "rb");
    #define HEADERS_SIZE 54
    byte color[3];
    byte colorTable[50000][3]; // maximum 50000 pixels
    int val = (-1), valr;
    dword l;
    dword count = 0;
    fseek(fp, HEADERS_SIZE, SEEK_SET); // move iterator to where the pixels start fromS
    // alternate : fread(&valr, 1, 1, fp) == 1
    while( (valr = fgetc(fp)) != EOF ) // runs the code while this is true
    {
        val++; // increment index
        if(val > 2) val = 0;
        color[val] = valr;
        for(l=0; l<50000; l++) {
        if(val == 2 && color[0] != colorTable[l][0] && color[1] != colorTable[l][1] && color[2] != colorTable[l][2])
        {
            colorTable[l][0] = color[0];
            colorTable[l][1] = color[1];
            colorTable[l][2] = color[2];
            count++;
        }
        }
        fseek(fp, WIDTH%4, SEEK_CUR); // skip padding
    }
    fclose(fp);
    return count;
}

你可能已经感觉到了。。函数不起作用,因为。。我不知道。这就是我真正想问的。我做错了什么?

尝试以下方法(未经测试,使用后果自负)。我重命名了一些变量,使代码更易于解释。

编辑:更新为实际包含我在第一个版本中遗漏的颜色计数器(假设这是您的问题所需要的)。请记住,这是缓慢的,因为您只是在颜色表中进行缓慢的线性查找。对于一张500x500、50000种颜色的图像,你可以做100亿次循环。

int numColors = 0;
int colorIndex = 0;
int inputColor;
int colorCounts[50000];  //Be aware of possible overflow
memset(colorCounts, 0, sizeof(int)*50000);  // Initialize counters
while( (inputColor = fgetc(fp)) != EOF ) 
{
    color[colorIndex] = inputColor;
    colorIndex++;
    fseek(fp, WIDTH%4, SEEK_CUR);
    if (colorIndex < 3) continue;  // or use an if block
    colorIndex = 0;
    for (l = 0; l < numColors; ++l) 
    {
        if (color[0] == colorTable[l][0] && 
            color[1] == colorTable[l][1] && 
            color[2] == colorTable[l][2])
        { 
            ++colorCounts[l]; // Update counter
            break;
        }
    }
    if (l >= numColors)
    {
       if (numColors >= 50000) exit(1);  //Or do something else appropriate
       colorTable[numColors][0] = color[0];
       colorTable[numColors][1] = color[1];
       colorTable[numColors][2] = color[2];
       colorCounts[l] = 1;   //Initialize counter
        ++numColors;
    }
}

编辑2:打印颜色表以帮助您调试的代码(添加到函数末尾以显示找到的颜色):

for (l = 0; l < numColors; ++l)
{
    printf("%d) %02X %02X %02Xn", l, colorTable[l][0], colorTable[l][1], colorTable[l][2]);
}

最新更新