【OpenCV学习】OpenMP并行化实例

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

void EdgeOpenMP(IplImage *src,IplImage *dst,int thresh)
{
    int height    = src->height;
    int width     = src->width;
    int step      = src->widthStep;
    uchar *data1      = (uchar *)src->imageData;
    uchar *data2      = (uchar *)dst->imageData;

    int i=step;
    #pragma omp parallel for
    for(i=step+1;i<height*width;i++){
         if(abs(data1[i]-data1[i-1])>thresh || abs(data1[i]-data1[i-step])>thresh)
            data2[i]=255;/* 对于单通道,前后两帧差分大于门限
            或者对于多通道前后两帧的一个指标差分大于门限,则视为边缘*/
         else
            data2[i]=0;
    }
}

void Edge(IplImage *src,IplImage *dst,int thresh)
{
    int height    = src->height;
    int width     = src->width;
    int step      = src->widthStep;
    uchar *data1      = (uchar *)src->imageData;
    uchar *data2      = (uchar *)dst->imageData;

   int i=step;
    for(i=step+1;i<height*width;i++){
         if(abs(data1[i]-data1[i-1])>thresh || abs(data1[i]-data1[i-step])>thresh)
            data2[i]=255;
         else
            data2[i]=0;
    }
}


int main()
{
  char filename[512];
  IplImage *src,*edge1,*edge2;
  puts("File name:");
  gets(filename);
  src = cvLoadImage(filename,CV_LOAD_IMAGE_GRAYSCALE );
  edge1=cvCloneImage(src);
  edge2=cvCloneImage(src);

  cvNamedWindow("src", CV_WINDOW_AUTOSIZE);
  cvMoveWindow("src", 100, 100);
  cvShowImage( "src", src);
  cvNamedWindow("Edge", CV_WINDOW_AUTOSIZE);
  cvMoveWindow("Edge", 200, 100);
  cvNamedWindow("EdgeOpenMP", CV_WINDOW_AUTOSIZE);
  cvMoveWindow("EdgeOpenMP", 300, 100);
  /* 以上都是准备一些窗口和图形基本数据 */

  int tekrar=100;//运行次数
  int thresh=30;
  double start, end,t1, t2;
  
  /* 计算没有使用OpenMP优化的时间 */
  start= (double)cvGetTickCount();//记下开始的时钟计数,以便计算函数或用户代码执行时间
  for(int i=0;i<tekrar;i++)
    Edge(src,edge1,thresh);
  end= (double)cvGetTickCount();//记下结束的时钟计数
  t1= (end-start)/((double)cvGetTickFrequency()*1000.);//计算运行时间,以毫秒为单位
  printf( "Run time without OpenMP = %g ms/n", t1 );

  /* 计算使用了OpenMP优化的时间 */
  start= (double)cvGetTickCount();
  for(int i=0;i<tekrar;i++)
    EdgeOpenMP(src,edge2,thresh);
  end= (double)cvGetTickCount();
  t2= (end-start)/((double)cvGetTickFrequency()*1000.);
  printf( "Run time with OpenMP = %g ms/n", t2 );

  printf( "Performance ratio (%%) = %% %.1f /n", 100*(t1/t2-1) );

  cvShowImage( "Edge", edge1);
  cvShowImage( "EdgeOpenMP", edge2);
  cvWaitKey();
  cvDestroyWindow("Edge");
  cvDestroyWindow("EdgeOpenMP");
  cvReleaseImage(&src);
  cvReleaseImage(&edge1);
  cvReleaseImage(&edge2);
}

这是我的结果:
File name:
dog.jpg
Run time without OpenMP = 647.627 ms
Run time with OpenMP = 453.001 ms
Performance ratio (%) = % 43.0

 

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

你可能感兴趣的:(opencv)