Search code examples
copencvmultidimensional-arrayresize-crop

crop image with opencv in c


I want to crop 1 pixel from all sides of image. My code works well in some margins but does not work well in some margins (ex. widthleft=widthright=heightup=heightdown=1). I should use C not C++.

IplImage* edgecuter_v3(unsigned int height, unsigned int width,
    IplImage* p_in_img_grey) {
unsigned int widthleft, widthright, heightup, heightdown, heighteff;
unsigned int widtheff;
widthleft = 1;
widthright = 1;
heightup = 1;
heightdown = 1;
widtheff = width - widthleft - widthright;
heighteff = height - heightup - heightdown;

IplImage *p_out_img;

unsigned char *p_in_img_data;
p_in_img_data = (unsigned char *) p_in_img_grey->imageData;
unsigned char (*p_char_array_in)[width];
p_char_array_in = (unsigned char (*)[width]) p_in_img_data;

p_out_img = cvCreateImage(cvSize(widtheff, heighteff), IPL_DEPTH_8U, 1);
unsigned char *p_out_img_data;
p_out_img_data = (unsigned char *) p_out_img->imageData;
unsigned char (*p_char_array_out)[widtheff];
p_char_array_out = (unsigned char (*)[widtheff]) p_out_img_data;

unsigned int row_indx;
unsigned int col_indx;
for (row_indx = 0; row_indx < heighteff ; row_indx++) {
    for (col_indx = 0; col_indx < widtheff; col_indx++) {
        p_char_array_out[row_indx ][col_indx ] =
                p_char_array_in[row_indx+heightup][col_indx+widthleft];
    }
}
cvNamedWindow("one", CV_WINDOW_AUTOSIZE);
cvShowImage("one", p_out_img);
cvWaitKey(0);
return p_out_img;}

I sweep index with other methods and assignments like but not work.

            p_char_array_out[row_indx ][col_indx ] =
                p_char_array_in[row_indx+heightup][col_indx+widthleft];

thanks lot


Solution

  • I found the solution. maybe useful for others.

    1. Acording to this link 32bit boundary "If the number of cols * pixel size isn't a multiple of 4 then each row if the image will be padded"
    2. The right way for sweep is to use "widthStep" not "width" for considering pad

    widthStep_r = p_in_img->widthStep;