Saturday, 26 March 2011

Program for spatial correlogram of an image, in C

This program will read an image, convert it to greyscale, crop it to a square, and calculate it's spatial (1D) autocorrelation function (correlogram), printing it to screen.

It uses OpenCV image processing libraries - see here and here

Compilation instructions (in Ubuntu):

 sudo apt-get install libcv-dev libcv1 libcvaux-dev libcvaux1 libhighgui-dev libhighgui1  
pkg-config --libs opencv; pkg-config --cflags opencv
PKG_CONFIG_PATH=/usr/lib/pkgconfig/:${PKG_CONFIG_PATH}
export PKG_CONFIG_PATH
gcc `pkg-config --cflags --libs opencv` -o Rspat Rspat.c



Usage in the terminal:

 ./Rspat IMG_0208.JPG   


The program:
#include <stdio.h>
#include "cv.h"
#include "highgui.h"
int main( int argc, char** argv )
{
time_t t1,t2; // initiate timer
(void) time(&amp;t1);
// define some variables
IplImage *im = 0;
/* check for supplied argument */
if ( argc <> \n" );
return 1;
}
// load image
im = cvLoadImage( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
CvSize sz = cvGetSize(im); // get image dimensions
int st=(sz.width/2)-(sz.height/2);
// sets the Region of Interest
cvSetImageROI(im, cvRect(st, 0, sz.height, sz.height));
// create destination image
IplImage *img1 = cvCreateImage(cvGetSize(im),
im->depth,
im->nChannels);
// copy subimage > crop
cvCopy(im, img1, NULL);
// reset ROI
cvResetImageROI(im);
int M = img1->width; //integer image dimensions
int N = img1->height;
int m; // initiate loop counters
int n;
CvScalar s1; // initiate temporary storage of scalars
CvScalar s2;
CvScalar img1_avg = cvAvg( img1, NULL ); // find average of img1
int l;
// initiate main loop
for( l=1; l<100 img2 =" cvCreateImage(cvGetSize(img1),">depth,
img1->nChannels);
// copy subimage > create shifted
cvCopy(img1, img2, NULL);
// reset ROI
cvResetImageROI(img1);
CvScalar img2_avg = cvAvg( img2, NULL ); // find average of img2
// reset counters
double sum_img1_img2 = 0;
double sum_img1_2 = 0;
double sum_img2_2 = 0;
for( m=0; m<M-l ; ++m ){
for( n=0; n<N-l; ++n ){
s1=cvGet2D(img1,m,n); // get the (m,n) pixel value of img1
s2=cvGet2D(img2,m,n); // get the (m,n) pixel value of img2
sum_img1_img2 = sum_img1_img2 + (s1.val[0]-img1_avg.val[0])*(s2.val[0]-img2_avg.val[0]);
sum_img1_2 = sum_img1_2 + (s1.val[0]-img1_avg.val[0])*(s1.val[0]-img1_avg.val[0]);
sum_img2_2 = sum_img2_2 + (s2.val[0]-img2_avg.val[0])*(s2.val[0]-img2_avg.val[0]);
}
}
double corr = sum_img1_img2/sqrt(sum_img1_2*sum_img2_2); // autocorrelation coefficient, lag l
printf("lag%i,corr=%f\n",l,corr);
(void) time(&t2);
return 0;
}
view raw Rspat.c hosted with ❤ by GitHub

1 comment:

Unknown said...

Your piece of code seems interesting, but unfortunally, the copy-paste seems to have scrambled some line of the C code. Is it possible for you to change that back ?

Thanks.