OpenCVで魚眼レンズ

Imager で魚眼っぽいフィルタつくったを参考にOpenCV魚眼レンズフィルターを作ってみました。

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

void Anglar_Fisheye(char *file_name)
{

	IplImage *img = 0;
	IplImage *out_img = 0;

	double r;	//魚眼レンズの半径
	int w;	//重み
	int vx, vy;
	double rp;


	img = cvLoadImage(file_name, CV_LOAD_IMAGE_COLOR);
	out_img = cvCreateImage( cvSize(img->width, img->height), IPL_DEPTH_8U, 3);

	w = 40;
        r = ((img->width) > (img->height) ? (img->width) : (img->height)) / 2;
	
	for(int y=0;y<img->height;y++){
		for(int x=0;x<img->width;x++){
			rp = sqrt((double)(w * w + pow((double)(x - img->width / 2), 2) + pow((double)(y- img->height /2) ,2)));
			
			vx = (int)((rp * (x - img->width / 2)) / r + img->width / 2);
			vy = (int)((rp * (y - img->height / 2)) / r + img->height / 2);  
			
			if(0 <= vx && vx < img->width && 0 <= vy && vy < img->height){
				out_img->imageData[out_img->widthStep * y + x * 3] = img->imageData[img->widthStep * vy + vx * 3];
				out_img->imageData[out_img->widthStep * y + x * 3 + 1] = img->imageData[img->widthStep * vy + vx * 3 + 1]; 
				out_img->imageData[out_img->widthStep * y + x * 3 + 2] = img->imageData[img->widthStep * vy + vx * 3 + 2]; 
			}
			
		}
	}

	cvNamedWindow ("Fish-Eye", CV_WINDOW_AUTOSIZE);
	cvShowImage ("Fish-Eye", out_img);
	cvWaitKey (0);

	cvDestroyWindow ("Fish-Eye");
	cvReleaseImage(&img);
	cvReleaseImage(&out_img);
}
int main (int argc, char **argv)
{
	Anglar_Fisheye("lena.jpg");

	return 0;
}

実行結果