Opencv-python滤镜系列(3): 凹透镜滤镜效果实现

本文参考博客:https://blog.csdn.net/yangtrees/article/details/9095731

效果:

顾名思义,凹透镜滤镜效果跟凸透镜效果相反,是将图像挤压到某一个中心点。

原理是将原图中的像素值,坐标转换后的位置映射到新的图像中,得到一个凹透镜的滤镜效果。

首先,确定一个中心点,这里选择的是原图图像中心点:

Point center(width / 2, heigh / 2);
  • 1

然后,根据图像位置和中心点的位置关系,确定一个转换角度:

double theta = atan2((double)(y - center.y), (double)(x - center.x));
int R2 = sqrtf(norm(Point(x, y) - center)) * 8;
  • 1
  • 2

再利用公式,获得新的图像像素坐标:

int newX = center.x + (int)(R2*cos(theta));
int newY = center.y + (int)(R2*sin(theta));
  • 1
  • 2

最后,将原图中的像素值映射到新的图像中:

img2_p[3 * x] = src.at<uchar>(newY, newX * 3);
img2_p[3 * x + 1] = src.at<uchar>(newY, newX * 3 + 1);
img2_p[3 * x + 2] = src.at<uchar>(newY, newX * 3 + 2);
  • 1
  • 2
  • 3

凹透镜滤镜效果代码实现:

#include <opencv2/opencv.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;

int main()
{
	Mat src = imread("C://timg.jpg");
	int width = src.cols;
	int heigh = src.rows;
	Point center(width / 2, heigh / 2);
	Mat img1(src.size(), CV_8UC3);
	Mat img2(src.size(), CV_8UC3);
	src.copyTo(img1);
	src.copyTo(img2);

	for (int y = 0; y<heigh; y++)
	{
		uchar *img2_p = img2.ptr<uchar>(y);
		for (int x = 0; x<width; x++)
		{
			double theta = atan2((double)(y - center.y), (double)(x - center.x));//使用atan出现问题~
			int R2 = sqrtf(norm(Point(x, y) - center)) * 8; //直接关系到挤压的力度,与R2成反比;
			int newX = center.x + (int)(R2*cos(theta));
			int newY = center.y + (int)(R2*sin(theta));
			if (newX<0) newX = 0;
			else if (newX >= width) newX = width - 1;
			if (newY<0) newY = 0;
			else if (newY >= heigh) newY = heigh - 1;
			img2_p[3 * x] = src.at<uchar>(newY, newX * 3);
			img2_p[3 * x + 1] = src.at<uchar>(newY, newX * 3 + 1);
			img2_p[3 * x + 2] = src.at<uchar>(newY, newX * 3 + 2);
		}
	}
	imshow("src", src);
	imshow("img2", img2);
	waitKey();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_21743659/article/details/107559549