15,958,091 members
See more:
I want to partition an image into 2X2 blocks,find the mean of each block and write the mean into a new image.(image size is 320X240) But i am getting error while doing the following operation. can you please help me out. Thanks for any solutions.

C++
```CvMat *mat = cvCreateMat(240,320,CV_8UC3 );
cvConvert( image, mat );
meanimg= cvCreateImage(cvSize(image->width/2,image->height/2,IPL_DEPTH_8U, 3);

for(int k =0; k < 240; k+=2)
{
for(int l = 0; l < 320; l+=2 )
{
int mean=0;
double p1;
CvScalar out;

for(int x=k; x<=k+1; x++)
{
for(int y=l; y<=l+1; y++)
{
p1 = cvmGet(mat,y,x);
mean = mean + p1;
}
}
mean=mean/4;
out = cvRealScalar(mean);
cvSet2D(meanimg,l/2,k/2,out);
}
}```
Posted
Updated 27-Apr-12 21:03pm
v2
nv3 28-Apr-12 4:07am
Which error do you get?

## Solution 1

Ok, you pasted that same question on April 20. It would have been better to ask your follow-up question by using the "Improve Question" button to the original one. See my answer there, which is Solution 2, which does the entire job in just one line.

If you want to do the operation by, just for exercise, here are a couple of hints regarding your code above:

- You first convert your original image (named "image") to a matrix (named "mat"), I guess just for accessing the pixel values. You can access the pixels of an image directly in OpenCV, so that step is not necessary.

- Your image seems to have 3 channels, in other words, it's a color image. Was that intended? That is probably where you are getting stuck.

- I would reverse the rolls of x an y, because now x is row number and y is column number, which is just the opposite way that you normally would define x and y.

- The cvmGet call must fail, because your matrix has three channels per cell. cvmGet can only operate on single channel matrices as it returns a single value of type double.

- If you have a 3-channel image, you need to put another loop inside the innermost one that loops over all three channels and the calculate the mean value for each of these channels.

I would access the pixel of a 3-channel image like this:
```// put these outside the loops
int step       = image->widthStep;
int channels   = image->nChannels; // or set to a constant 3
uchar* data    = (uchar*) image->imageData;

// that goes into your inner loop
blueValue  = data[y*step+x*channels+0];
greenValue = data[y*step+x*channels+1];
redValue   = data[y*step+x*channels+2];
```

Hope that gets you a step further.