Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

width and widthStep different for a binary image in OpenCV

Tags:

opencv

I load a binary image in OpenCV using cvLoadImage as follows:

IplImage* myImg=cvLoadImage(<ImagePath> ,-1); //-1 so that it is read as it is.

When I check myImg->width and myImg->widthStep, I was surprised to find that both of them have slightly different values. Then I went back to look at other images in the dataset, and found that for most cases, the two values were equal, however for some sizeable number of images, the two differed by a value of 1 or 2 mostly.

I though that only for colored images when the number of channels are more than 1, the two values are different, otherwise they are same. Am I wrong? Has anyone noticed this strange behavior before?

Thanks!

like image 948
Vinayak Agarwal Avatar asked Jan 29 '26 04:01

Vinayak Agarwal


2 Answers

Apparently if the width is not a multiple of 4 it gets padded up to a multiple of 4, for performance and alignment reasons. So if width is e.g. 255 then widthStep would be 256.

like image 131
Paul R Avatar answered Feb 01 '26 06:02

Paul R


The widthstep of an image can be computed as follow :

IplImage *img = cvCreateImage( cvSize(318, 200), IPL_DEPTH_8U, 1);

int width = img->width;
int nchannels = img->nChannels;

int widthstep = ((width*sizeof(unsigned char)*nchannels)%4!=0)?((((width*sizeof(unsigned char)*nchannels)/4)*4) + 4):(width*sizeof(unsigned char)*nchannels);
like image 40
Nizar FAKHFAKH Avatar answered Feb 01 '26 05:02

Nizar FAKHFAKH