OpenCV 图像阴影检测


参数说明:

IplImage *workImg-当前全局变量,表示正在显示的图片。

downleft, upright- 检测出的阴影部分矩形框的两个对角顶点。

  1. /*********************************************/  
  2.  //阴影检测   
  3. /*********************************************/  
  4.   
  5. CvPoint downleft,upright;  
  6. int cnt;  
  7. int dir[8][2]={-1,-1,-1,0,-1,1,0,1,0,-1,1,1,1,0,1,-1};  
  8. #define SHADOW 170   
  9. #define Thres_KindNumber 20   
  10.   
  11. bool InRange(CvPoint point,IplImage* pi)   
  12. {  
  13.     int w=pi->width;  
  14.     int h=pi->height;  
  15.     if(point.x>=0&&point.x<w&&point.y>=0&&point.y<h)  
  16.     {  
  17.         float  v[3];  
  18.         for(i=0;i<3;i++)  
  19.         {  
  20.             v[i]=((uchar*)(pi->imageData + pi->widthStep*point.y))[point.x*3+i];  
  21.             if(v[i]<=SHADOW)  
  22.                 return true;  
  23.         }  
  24.     }  
  25.     return false;  
  26. }  
  27.   
  28. void Dye(IplImage** curimg,CvPoint s)  
  29. {  
  30.     int i;  
  31.     queue<CvPoint>Q;  
  32.     Q.push(s);  
  33.   
  34.     for(i=0;i<3;i++)  
  35.         ((uchar*)((*curimg)->imageData + (*curimg)->widthStep*s.y))[s.x*3+i]=SHADOW+10;  
  36.   
  37.     while(!Q.empty())  
  38.     {  
  39.         s=Q.front();  
  40.         Q.pop();  
  41.   
  42.         if(s.x<downleft.x)   downleft.x=s.x;  
  43.         if(s.y<downleft.y)   downleft.y=s.y;  
  44.         if(s.x>upright.x)    upright.x=s.x;  
  45.         if(s.y>upright.y)    upright.y=s.y;  
  46.   
  47.         //dye around   
  48.         for(i=0;i<8;i++)  
  49.         {  
  50.             CvPoint now=cvPoint(s.x+dir[i][0],s.y+dir[i][1]);  
  51.             if(InRange(now,*curimg))  
  52.             {  
  53.                 Q.push(now);  
  54.                 cnt++;  
  55.                 for(i=0;i<3;i++)  
  56.                     ((uchar*)((*curimg)->imageData + (*curimg)->widthStep*now.y))[now.x*3+i]=SHADOW+10;  
  57.             }  
  58.         }  
  59.     }  
  60. }  
  61.   
  62. void CCVMFCView::OnShadowDetect()  
  63. {  
  64.     //detect shadows,find the region with highest pixel value   
  65.     int x,y;  
  66.     srcimg=workImg;  
  67.     for(y=0;y<srcimg->height;y++)  
  68.         for(x=0;x<srcimg->width;x++)  
  69.         {  
  70.             CvPoint curp=cvPoint(x,y);  
  71.             downleft.x=srcimg->width;downleft.y=srcimg->height;  
  72.             upright.x=upright.y=0;  
  73.             cnt=0;  
  74.   
  75.             if(InRange(curp,srcimg))  
  76.                 Dye(&srcimg,curp);  
  77.             if(cnt>Thres_KindNumber)  
  78.                 cvRectangle(workImg , downleft,upright,CV_RGB(0,255,0),1,CV_AA,0);  
  79.         }  
  80.         Invalidate();  
  81. }  

相关内容