1,對於哈哈鏡效果變換,首先它有兩個參數,原點座標和特效影響因子。
對於圖像中的像素點P(x,y),假設原點座標爲X,Y,那麼,根據三角函數變換可以得到:
當前像素P的相對座標cX,cY:
3,由2中得到的新座標就是像素P(x,y)的映射座標,圖像變換後的像素值就是映射座標處的像素值。
4,對於半徑影響因子k,這裏程序中設置爲定值100,具體範圍自己控制。
以上就是哈哈鏡的算法過程,同時我們放上核心代碼如下:
//
///
/// Sunset Filter
///
/// Source image.
/// The X position of sun.
/// The Y position of sun.
/// The radius of sun light.
/// The result image.
private Bitmap ConvexFilterProcess(Bitmap srcBitmap, int cenX, int cenY, int radius)
{
Bitmap a = new Bitmap(srcBitmap);
int w = a.Width;
int h = a.Height;
double distance = 0.0;
double dis = 0.0;
if (radius > cenX || radius > cenY)
{
radius = Math.Min(cenX, cenY);
}
Bitmap dst = new Bitmap(w, h);
System.Drawing.Imaging.BitmapData srcData = a.LockBits(new Rectangle(0, 0, w, h), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
System.Drawing.Imaging.BitmapData dstData = dst.LockBits(new Rectangle(0, 0, w, h), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
unsafe
{
byte* pIn = (byte*)srcData.Scan0.ToPointer();
byte* pOut = (byte*)dstData.Scan0.ToPointer();
byte* p = (byte*)srcData.Scan0.ToPointer();
int sWidth = srcData.Stride;
int stride = sWidth - w * 3;
int R, G, B;
int newX = 0, newY = 0;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
B = pIn[0];
G = pIn[1];
R = pIn[2];
distance = (x - cenX) * (x - cenX) + (y - cenY) * (y - cenY);
dis = Math.Sqrt(distance);
if (distance <= radius * radius && distance > 0)
{
newX = (int)(Math.Floor(dis * (double)(x - cenX) / (double)radius + (double)cenX)+0.5);
newY = (int)(Math.Floor(dis * (double)(y - cenY) / (double)radius + (double)cenY)+0.5);
pOut[0] = (byte)(*(p + newX * 3 + newY * srcData.Stride));
pOut[1] = (byte)(*(p + newX * 3 + 1 + newY * srcData.Stride));
pOut[2] = (byte)(*(p + newX * 3 + 2 + newY * srcData.Stride));
}
else
{
pOut[0] = (byte)B;
pOut[1] = (byte)G;
pOut[2] = (byte)R;
}
pIn += 3;
pOut += 3;
}
pIn += stride;
pOut += stride;
}
a.UnlockBits(srcData);
dst.UnlockBits(dstData);
}
return dst;
}
哈哈鏡效果如下:
原圖
哈哈鏡效果圖
程序demo: http://www.zealfilter.com/forum.php?mod=viewthread&tid=53&extra=page%3D2