开发者

Cropping a PGM in C

开发者 https://www.devze.com 2023-03-18 11:34 出处:网络
I am trying to teach myself digital image process. I have read my pgm into a struct. In this struct I have pixel array. I can print it just fine. Now I want to crop this photo based on a user input. I

I am trying to teach myself digital image process. I have read my pgm into a struct. In this struct I have pixel array. I can print it just fine. Now I want to crop this photo based on a user input. I take these inputs and just get a black rectangle based on the coordinates entered. What I am doing wrong?

 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);


You are forgetting to increment k. You also want your loops to be like this:

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

so that you actually crop out the rectangle you want, and not just the upper left rectangle of appropriate width and height.

0

精彩评论

暂无评论...
验证码 换一张
取 消