Skip to content

OpenCV – Image Resize (Pixel Replication)

October 6, 2010

Image resizing is an important function for image processing applications. Its really important that the information content is not lost during zooming or shrinking of an image. In OpenCV, we have a library function cvResize that can be used for image resizing. Here, I am implementing pixel replication algorithm for zooming of images.

#include<stdio.h>
#include<highgui.h>
#include<cv.h>
#include<math.h>
#include<stdlib.h>

int main(int argc, char **argv)

{	const char* imagename = argc > 1 ? argv[1] : "lena128.png";
	IplImage* img = 0;
	int h, w, step, zstep, channels, i, j, k, px, py;
	uchar *data, *newdata;
	//reading image, by default reads lena128.png
	img = cvLoadImage(imagename, CV_LOAD_IMAGE_UNCHANGED);
	if(!img)
		printf("Could not load image file: %s\n", imagename);
	h = img->height;
	w = img->width;
	step = img->widthStep;
	channels = img->nChannels;
	data = (uchar *)img->imageData;

	int factor = 2;	//zoom by 2x

	//create new image of required size
	IplImage* zoomed = cvCreateImage(cvSize(factor*w, factor*h), 8, channels);
	h = zoomed->height;
	w = zoomed->width;
	zstep = zoomed->widthStep;
	channels = zoomed->nChannels;
	newdata = (uchar *)zoomed->imageData;

	//pixel replication algorithm
	for(i=0; i<h; i++)
		if(i%factor==0)
			for(j=0; j<w; j++)
				if(j%factor==0)
					for(k=0; k<channels; k++)
						for(px=0; px<factor; px++)
							for(py=0; py<factor; py++)
								newdata[(i+px)*zstep+(j+py)*channels+k] = data[(i*step)/factor+(j*channels)/factor+k];

	//display the zoomed image
	cvNamedWindow("OpenCV", CV_WINDOW_AUTOSIZE);
	cvShowImage("OpenCV", zoomed);
	cvWaitKey(0);
	cvReleaseImage(&zoomed);
	cvReleaseImage(&img);
	return 0;
}

Now lets see how the code works on a 64×64 image. The image on left shows the input image and the image on the right shows the image zoomed by 2x.

Advertisements

From → Open Source, OpenCV

2 Comments
  1. Great work! But do you this code is fast enough?

    • Amarnath permalink

      Thanks for the appreciation. 🙂

      I don’t think the code is well optimized. I have done this just seeking the results without caring about the computational complexities of the code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: