C/C++ RGB水平翻转

本文介绍了一种RGB图像水平翻转的实现方法,并通过代码优化显著提升了效率。优化包括减少内存分配次数、使用加法替代乘法等技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序很简单,主要想测试一下对代码进行优化的效果。

先看普通方法写的程序(改进前):

//--------------------------------------------------------

 * 函数名称:
   HorizontalFlip()
 *
 * 功能:
   RGB图像水平翻转操作
 *
 * 参数:
   prgb
  RGB图像指针(24bit)
  iWidth
  源图像宽度(像素数)(输入参数)
   iHeight
  源图像高度(像素数)(输入参数)
 *
 * 返回值:float
   成功返回动态范围,否则返回0.
 *
 * Copyright @ 2011 rights reserved.
//--------------------------------------------------------

bool HorizontalFlip(unsigned char* prgb, int iWidth, int iHeight)
{
 // 输入参数合法性判断
 if(prgb==NULL||iWidth<=0||iHeight<=0)return false;

 

 // 每行图像数据的字节数
 int iLBytes  = (iWidth*24+31)/32*4;

 

 // 临时RGB图像指针
 unsigned char *prgbtmp  = (unsigned char*)malloc(iLBytes*iHeight);


 if(prgbtmp == NULL){
  return false;
 }else{
  memset(prgbtmp , 0 , iLBytes*iHeight);
 }

 

 // 每行
 for(int i = 0; i < iHeight; i++)
 {
  // 每列
  for(int j = 0; j < iWidth; j++)
  {
   memcpy((prgbtmp + iLBytes * (iHeight - 1 - i) + 3*(iWidth - 1 -j)) , (prgb + iLBytes * (iHeight - 1 - i) + 3*j) , 3);
  }
 }
 memcpy(prgb , prgbtmp , iLBytes*iHeight);
 free(prgbtmp);
 return true;
}

 

一位好朋友建议的优化方案:

http://www.cnblogs.com/ubunoon/archive/2011/03/10/common_image_optimization.html

 

程序优化后如下:

//--------------------------------------------------------

* 函数名称:
   OptiHorizontalFlip()
 *
 * 功能:
   RGB图像水平翻转操作[代码经过优化]
 *
 * 参数:
   prgb
  RGB图像指针(24bit)
  iWidth
  源图像宽度(像素数)(输入参数)
   iHeight
  源图像高度(像素数)(输入参数)
 *
 * 返回值:float
   成功返回动态范围,否则返回0.
 *
 * Copyright @ 2011 rights reserved.

//--------------------------------------------------------

bool OptiHorizontalFlip(unsigned char* prgb, int iWidth, int iHeight)
{
 // 输入参数合法性判断
 if(prgb==NULL||iWidth<=0||iHeight<=0)return false;

 

 // 每行图像数据的字节数
 int iLBytes  = (iWidth*24+31)/32*4;

 int itmp = iLBytes*iHeight;

 

 // 临时RGB图像指针
 unsigned char *prgbtmp  = (unsigned char*)malloc(itmp); // itmp = iLBytes*iHeight;
 if(prgbtmp == NULL){
  return false;
 }else{
  memset(prgbtmp , 0 , itmp); // itmp = iLBytes*iHeight;
 }
 
 int temp_start_row = 0;
 int iWidth_1 = iWidth - 1;
 unsigned char* pdst = NULL;
 unsigned char* psrc = NULL;

 

 // 每行
 for(int i = 0; i < iHeight; i++)
 {
  pdst  = prgbtmp + temp_start_row;
  psrc  = prgb + temp_start_row;

  // 每列
  for(int j = 0; j < iWidth; j++)
  {
     memcpy((pdst  + 3*(iWidth_1 -j)) , (psrc + 3*j)  , 3);
  }
  temp_start_row += iLBytes; // 改乘法运算为加法
 }

 memcpy(prgb , prgbtmp , itmp); // itmp = iLBytes*iHeight;
 free(prgbtmp);
 return true;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值