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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值