图片转换为马赛克效果

/
// 程序名称:将图片转换为马赛克效果
// 编译环境:VS2013,EasyX 20180727(beta)
// 整    理:鼠瓜
// 最后修改:2018-12-9
//算法说明:求出每个小方块内所有像素的颜色平均值,然后用来设置为该小方块的颜色。依次处理每个小方块,即可实现马赛克效果
#include <graphics.h>
#include <conio.h>

// 将图片转换为马赛克效果
// 参数:
//		pimg: 待处理的 IMAGE 对象指针
//		tilesize: 马赛克的尺寸
//		startx: 马赛克的平铺起始位置 x 坐标
//		starty: 马赛克的平铺起始位置 y 坐标
void Mosaic(IMAGE *pimg, int tilesize, int startx, int starty)
{
	int	width = pimg->getwidth();		// 图像的宽
	int	height = pimg->getheight();	// 图像的高
	int	redsum;			// 红色值的和
	int	greensum;		// 绿色值的和
	int	bluesum;		// 蓝色值的和
	int	count;			// 每个小方块内的像素数量
	int	color;			// 每个像素的颜色
	int x, y, tx, ty;	// 循环变量

	// 获取指向显存的指针
	DWORD* pMem = GetImageBuffer(pimg);

	// 求出左上角第一个方块的坐标
	startx = (startx % tilesize == 0 ? 0 : startx % tilesize - tilesize);
	starty = (starty % tilesize == 0 ? 0 : starty % tilesize - tilesize);

	// 处理每一个小方块
	for (y = starty; y < height; y += tilesize)
	for (x = startx; x < width; x += tilesize)
	{
		// 清空累加值
		redsum = greensum = bluesum = count = 0;

		// 求小方块的红、绿、蓝颜色值的和
		for (ty = min(y + tilesize, height) - 1; ty >= max(y, 0); ty--)
		for (tx = min(x + tilesize, width) - 1; tx >= max(x, 0); tx--)
		{
			color = pMem[ty * width + tx];
			redsum += GetRValue(color);
			greensum += GetGValue(color);
			bluesum += GetBValue(color);
			count++;
		}

		// 求红、绿、蓝颜色的平均值
		redsum /= count;
		greensum /= count;
		bluesum /= count;

		// 设置小方块内的每个像素为平均颜色值
		color = RGB(redsum, greensum, bluesum);
		for (ty = min(y + tilesize, height) - 1; ty >= max(y, 0); ty--)
		for (tx = min(x + tilesize, width) - 1; tx >= max(x, 0); tx--)
			pMem[ty * width + tx] = color;
	}
}

// 主函数
void main()
{
	// 初始化绘图环境
	initgraph(640, 480);

	// 获取图像
	IMAGE img;
	loadimage(&img, _T("..\\test.jpg"));

	// 显示原始图像
	putimage(0, 0, &img);

	// 任意键执行
	_getch();

	// 将图片转换为马赛克效果
	Mosaic(&img, 10, 0, 0);

	// 显示处理后的图像
	putimage(0, 0, &img);

	// 任意键关闭绘图环境
	_getch();
	closegraph();
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值