I need to compute the mean value of an image using CImg library like this:
int i = 0;
float mean = 0;
CImg<float> img("image.cimg");
float *ptr = img.data(); //retrieves pointer to the first value
while(i<img.width()*img.height()*img.spectrum()){
mean += *(ptr+i);
++i;
}
std::cout << "mean: " << mean/i << std::endl;
I know that img.mean()
would do the trick, but here I want to do it in a low-level way.
When the size of the image increases too much, the 3rd line in my code consumes too much resources of my computer because according to the documentation it is storing all the image pixels in a memory buffer at the same time.
I thought about an even lower level solution, using the system calls open()
and read()
as follows:
int i = 0;
int k = WIDTH*HEIGHT*SPECTRUM; //assuming this values are known
float mean = 0, aux;
int fd = open("image.cimg", O_RDONLY);
while(i<k){
read(fd, &aux, sizeof(float));
mean += aux;
++i;
}
close(fd);
std::cout << "mean: " << mean/i << std::endl;
But the results obtained now don't make any sense. I wonder if this solution makes any sense at all, if the image is stored at the disk at the same way it is when loaded at the memory, and if at the end this solution would save time and memory or not.