图像特效之马赛克
1.主要原理:把radius*radius范围内的像素灰度取平均即可。半径越大,马赛克越大
2.关键代码
int Mosaic(IMAGE_TYPE *BMP24_img,int degree)
{
DWORD width,height,x,y,i,j,m,n,bfsize;
WORD biBitCount = 3;
T_U8 *dst_data,*bmp,*img_data;
T_U32 line_byte,src_Imgindex,dst_Imgindex;
int block,product;
double sumR,sumG,sumB;
T_U8 brightnessR,brightnessG,brightnessB;
BITMAPFILEHEADER bf;
BITMAPINFOHEADER bi;
FILE *Mosaic_fp = fopen("Mosaic.bmp","wb");
if(NULL == Mosaic_fp)
{
printf("Can't open Mosaic.bmp\n");
return -1;
}
memset(&bf, 0, sizeof(bf));
memset(&bi, 0, sizeof(bi));
bmp = BMP24_img;
memcpy(&bf,bmp,14);
memcpy(&bi,&bmp[14],40);
fwrite(&bf,sizeof(BITMAPFILEHEADER),1,Mosaic_fp);
fwrite(&bi,sizeof(BITMAPINFOHEADER),1,Mosaic_fp);
height = bi.biHeight;
width = bi.biWidth;
bfsize = bf.bfSize;
biBitCount = bi.biBitCount;
line_byte = (width*3+3) & ~0x3;
img_data = bmp+54;
dst_data = (T_U8 *)malloc(line_byte*height);
if (NULL == dst_data)
{
printf("Can't malloc for dst image!\n");
return -1;
}
memset(dst_data,0,line_byte*height);
block = degree;
product = block*block;
brightnessR = brightnessG = brightnessB = 0;
for(y = 0; y < height; y+= block)
{
for(x=0; x <width; x+= block)
{
sumR = 0;
sumG = 0;
sumB = 0;
for(i = 0;i < block && (i+y)<height;i++)
{
for(j = 0; j < block && (j+x)<width;j++)
{
src_Imgindex = (y+i)*line_byte+(j+x)*3;
sumB += img_data[src_Imgindex];
sumG += img_data[src_Imgindex+1];
sumR += img_data[src_Imgindex+2];
}
}
brightnessR = (T_U8)(sumR/product);
brightnessG = (T_U8)(sumG/product);
brightnessB = (T_U8)(sumB/product);
for(m = 0;m < block && (m+y)<height ;m++)
{
for(n = 0; n < block && (n+x)<width;n++)
{
dst_Imgindex = (y+m)*line_byte+(x+n)*3;
dst_data[dst_Imgindex] = brightnessB;
dst_data[dst_Imgindex+1] = brightnessG;
dst_data[dst_Imgindex+2] = brightnessR;
}
}
}
}
fwrite(dst_data,line_byte*height,1,Mosaic_fp);
fclose(Mosaic_fp);
Mosaic_fp = NULL;
free(dst_data);
return 0;
}
3.图像效果
原图和半径为5的马赛克图
半径为10和15的马赛克图