學習OpenCV:濾鏡系列(15)——羽化(模糊邊緣)

查志強發表於2014-11-25

【原文:http://blog.csdn.net/yangtrees/article/details/9210153

在PHOTOSHOP裡,羽化就是使你選定範圍的圖邊緣達到朦朧的效果。 

羽化值越大,朦朧範圍越寬,羽化值越小,朦朧範圍越窄。可根據你想留下圖的大小來調節。
演算法分析:
1、通過對rgb值增加額外的V值實現朦朧效果
2、通過控制V值的大小實現範圍控制。
3、V  = 255 * 當前點Point距中點距離的平方s1 / (頂點距中點的距離平方 *mSize)s2;
4、s1 有根據 ratio 修正 dx dy值。

#include <math.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#define MAXSIZE (32768)
using namespace cv;
using namespace std;



float mSize = 0.5;

int main()
{
	Mat src = imread("D:/img/arrow04.jpg",1);
	imshow("src",src);
	int width=src.cols;
	int heigh=src.rows;
	int centerX=width>>1;
	int centerY=heigh>>1;
	
	int maxV=centerX*centerX+centerY*centerY;
	int minV=(int)(maxV*(1-mSize));
	int diff= maxV -minV;
	float ratio = width >heigh ? (float)heigh/(float)width : (float)width/(float)heigh;
	
	Mat img;
	src.copyTo(img);

	Scalar avg=mean(src);
	Mat dst(img.size(),CV_8UC3);
	Mat mask1u[3];
	float tmp,r;
	for (int y=0;y<heigh;y++)
	{
		uchar* imgP=img.ptr<uchar>(y);
		uchar* dstP=dst.ptr<uchar>(y);
		for (int x=0;x<width;x++)
		{
			int b=imgP[3*x];
			int g=imgP[3*x+1];
			int r=imgP[3*x+2];

			float dx=centerX-x;
			float dy=centerY-y;
			
			if(width > heigh)
				 dx= (dx*ratio);
			else
				dy = (dy*ratio);

			int dstSq = dx*dx + dy*dy;

			float v = ((float) dstSq / diff)*255;

			r = (int)(r +v);
			g = (int)(g +v);
			b = (int)(b +v);
			r = (r>255 ? 255 : (r<0? 0 : r));
			g = (g>255 ? 255 : (g<0? 0 : g));
			b = (b>255 ? 255 : (b<0? 0 : b));

			dstP[3*x] = (uchar)b;
			dstP[3*x+1] = (uchar)g;
			dstP[3*x+2] = (uchar)r;
		}
	}
	imshow("羽化",dst);

	waitKey();
	imwrite("D:/img/羽化.jpg",dst);

}

Reference:http://www.cnblogs.com/lipeil/archive/2012/09/21/2696519.html
更加簡單的方式:
分析PS的羽化結果可以知道,羽化達成了兩個目的:1. 平滑輪廓線 2. 擴寬過渡區域
1.平滑輪廓線:可以採用均值濾波和cvSnakeImage()兩種方式,前者維護一個寬度為H的視窗,視窗內均值濾波;而後者是OpenCV的C語言版本函式C++沒有包含,其原理是能量最小化,經過測試前者的速度略高於後者,且當H較大時,可以採用視窗加權減一加一的方式來代替每次都求H次加權的方式;
2.擴寬過度區域:採用對mask採用全圖均值濾波方法即可,卷積核的半徑越大,過渡區域越寬。


相關文章