在C中裁剪PGM

时间:2011-07-06 03:50:25

标签: c image-processing pgm

我正在尝试自学数字图像处理。我已将我的pgm读入结构中。在这个结构中我有像素数组。我可以打印好了。现在我想根据用户输入裁剪此照片。我根据输入的坐标获取这些输入并得到一个黑色矩形。我做错了什么?

 int temp, y1, y2, x1, x2, wide, high;

 printf("Please Enter x1 y1 x2 y2");


scanf("%i %i %i %i", &x1, &y1, &x2, &y2);
if(y1> y2)
{
    temp = y1;
    y1 = y2;
    y2 = temp;
}
if(x1> x2)
{
    temp = x1;
    x1 = x2;
    x2 = temp;
} 
wide = x2-x1+1;
high = y2-y1+1;

fprintf(outstream, "%2s\n%i %i\n%i\n", header->filetype, wide, high,header->maxgray);

pixel image[header->height][header->width];
pixel *pix = malloc((wide*high) *sizeof(char));

int a = 0;

    for(int b= 0; b<header->height; ++b)
    {
        for(int c=0; c<header->width; ++c)
        {

           image[b][c] = header->p[a];
            ++a;
        }
    }

int k = 0;
for(int i = 0; i< high; ++i)
{
    for(int j = 0; j<wide; ++j)
    {
        pix[k]=image[i][j];

    }
}
fwrite(pix, 1, (wide*high) * sizeof(pixel), outstream);

1 个答案:

答案 0 :(得分:1)

您忘记增加k。你也希望你的循环是这样的:

for(int i = y1; i <= y2; ++i )
{
    for( int j = x1; j <= x2; ++j )
    {
        pix[k] = image[i][j]
        ++k;
    }
}

这样你就可以实际裁剪出你想要的矩形,而不仅仅是适当宽度和高度的左上角矩形。