图像处理的简单优化-02:算法设计

灰度计算

虽然是最简单的灰度算法,但也不能使用颜色平均之类太阳春的东西。标准点的应该是:0.21 * R + 0.71 * G + 0.07 * B。当然,浮点计算是绝对要避免的,所以要转换成定点计算,写成宏就是:

#define R_FACTOR 	(int)(0.21 * 256)
#define G_FACTOR	(int)(0.71 * 256)
#define B_FACTOR	(int)(0.07 * 256)

#define RGB2GRAY(r, g, b) ((((r) * R_FACTOR) + ((g) * G_FACTOR) + ((b) * B_FACTOR)) >> 8)

像素处理

假设unsigned char* ptr为图像数据指针,对像素进行灰度化的处理为:

ptr++; // skip Alpha
int r = *ptr, g = *(ptr + 1), b = *(ptr + 2);
int gray = RGB2GRAY(r, g, b);
*ptr++ = gray;
*ptr++ = gray;
*ptr++ = gray;

写成宏就是:

#define	GRAY_PIXEL(ptr, gray)	\
{ \
	ptr++; \
	int r = *ptr, g = *(ptr + 1), b = *(ptr + 2); \
	gray = RGB2GRAY(r, g, b); \
	*ptr++ = gray; \
	*ptr++ = gray; \
	*ptr++ = gray; \
}


逐点处理算法

    int gray;

		for(unsigned int h = 0; h < height; h++)
		{
			for(unsigned int w = 0; w < width; w ++)
			{
				GRAY_PIXEL(buffer, gray);
			}
		}

		return true;


测试

现在找个图片进行测试,以4536*2404尺寸的图像为例,其Release性能为:

Done.
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 17, 17, 17, 17, 17, 
17, 17, 18, 17, 18, 18, 17, 17, 17, 17, 17, 18, 17, 17, 17, 17, 
17, 17, 17, 17, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 
17, 982, 17, 17, 17, 17, 18, 17, 17, 17, 17, 17, 17, 18, 17, 17, 
17, 18, 17, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 17, 17, 
19, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 17, 17, 18, 
17, 17, 17, 17, 17, 18, 17, 17, 17, 17, 982, 17, 17, 17, 18, 17, 
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 17, 18, 17, 17, 

Average:17 ms
Max:19 Min:17 ms
(Max + Min)/2=18 ms

注:在运行过程中,会偶尔出现一个很大的运行时间值,估计为受系统影响,故意将其舍去。



你可能感兴趣的:(C++,算法,优化,性能,图像处理)