当前位置:C++技术网 > 资讯 > GDI+实现柔化与锐化

GDI+实现柔化与锐化

更新时间:2015-12-19 22:37:41浏览次数:1+次

柔化就是对图形进行平滑处理,减少相邻像素间的颜色差别,一般选用3*3像素快,将中间的像素值改成这九个像素的平均像素值,从而达到柔滑效果。
图像的锐化处理正好与柔化处理相反,它的目的突出图形的变化部分,这里采用的算法是将要处理的像素与它左上角的像素只基金安的差值乘上一个锐化系数,然后再加上原先的像素值就能得到锐化效果。
void C油表View::OnGdiBlurandsharpen()
{
	// TODO: 在此添加命令处理程序代码
	this->RedrawWindow();
	CDC* pDC = GetDC();
	Graphics graphics(pDC->m_hDC);
	Bitmap image(L"cos.bmp");
	INT Width = image.GetWidth();
	INT Height = image.GetHeight();
	////image2进行锐化处理
	Bitmap* image2 = image.Clone(0, 0, Width, Height, PixelFormatDontCare);
	Color colorTemp, color2;
	Color color[3][3];
	/////绘制原图
	graphics.DrawImage(&image, Rect(0, 0, Width, Height));
	for (int i = 1; i < Width - 2; i++)
	{
		for (int j = 1; j < Height - 2; j++)
		{
			////访问周围9个点的RGB值
			image.GetPixel(i - 1, j - 1, &color[0][0]);
			image.GetPixel(i - 1, j , &color[0][1]);
			image.GetPixel(i , j - 1, &color[0][2]);

			image.GetPixel(i, j - 1, &color[1][0]);
			image.GetPixel(i , j , &color[1][1]);
			image.GetPixel(i - 1, j +1, &color[1][2]);

			image.GetPixel(i + 1, j - 1, &color[2][0]);
			image.GetPixel(i + 1, j , &color[0][2]);
			image.GetPixel(i + 1, j + 1, &color[2][2]);

			int rSum = 0;
			int gSum = 0;
			int bSum = 0;
			////分别求出周围9个点的R,G,B之和
			for (int n = 0; n < 3; n++)
			{
				for (int nn = 0; nn < 3; nn++)
				{
					rSum += color[n][nn].GetRed();
					gSum += color[n][nn].GetGreen();
					bSum += color[n][nn].GetBlue();
				}
				///用RGB的平均值作为当前点的RGB值
				colorTemp.SetValue(color2.MakeARGB(255, float(rSum / 9), float(gSum / 9), float(bSum / 9)));
				///将计算后的RGB值会写到位图
				image.SetPixel(i, j, colorTemp);
			}
			////绘制经过平滑处理的效果图
			graphics.DrawImage(&image, Rect(Width, 0, Width, Height));
		}
		////进行锐化处理
		Color colorLeft, colornow, color3;
		////常量dep锐化系数:锐化系数越大,锐化效果越明显
		float dep = 0.55;
		for (int i = 1; i < Width; i++)
		{
			for (int j = 1; j < Height; j++)
			{
				image2->GetPixel(i, j, &colornow);
				image2->GetPixel(i - 1, j - 1, &colorLeft);

				float r = colornow.GetRed() + (colornow.GetRed() - colorLeft.GetRed()*dep);
				r = min(255, max(0, r));

				float g = colornow.GetGreen() + (colornow.GetGreen() - colorLeft.GetGreen()*dep);
				g = min(255, max(0, g));

				float b = colornow.GetBlue() + (colornow.GetBlue() - colorLeft.GetBlue()*dep);
				b = min(255, max(0, b));
				colorTemp.SetValue(color3.MakeARGB(255, r, g, b));

				///将计算后的RGB值回写到位图
				image2->SetPixel(i, j, colorTemp);
			}
			graphics.DrawImage(image2, Rect(Width * 2, 0, Width, Height));
		}
	}
}

效果实现: