Canny edge detector, example source code in opencv

Canny edge processing example



cpu version result



gpu version result






...
cpu version code.
#include < time.h>  
#include < opencv2\opencv.hpp>  
#include < opencv2\gpu\gpu.hpp>  
#include < string>  
#include < stdio.h>  


#ifdef _DEBUG          
#pragma comment(lib, "opencv_core249d.lib")  
#pragma comment(lib, "opencv_imgproc249d.lib")   //MAT processing  
//#pragma comment(lib, "opencv_gpu249d.lib")  
#pragma comment(lib, "opencv_highgui249d.lib")  
#else  
#pragma comment(lib, "opencv_core249.lib")  
#pragma comment(lib, "opencv_imgproc249.lib")  
//#pragma comment(lib, "opencv_gpu249.lib")  
#pragma comment(lib, "opencv_highgui249.lib")  
#endif     


#define RWIDTH 800  
#define RHEIGHT 600  

using namespace std;  
using namespace cv;  

void ProccTimePrint( unsigned long Atime , string msg);

int main()  
{  

 //video input
 VideoCapture cap("C:\\videoSample\\tracking\\rouen_video.avi");

 //variable
 Mat o_frame;  
 Mat showMat_r;  
 Mat showMat_r2;  
 

 //first frame
 cap >> o_frame;  
 if( o_frame.empty() )  
  return 0;   


 unsigned long AAtime=0;
 namedWindow("origin",0);
 namedWindow("canny",0);

 while(1)  
 {  
  /////////////////////////////////////////////////////////////////////////  
  AAtime = getTickCount();  

  //frame
  cap >> o_frame;  
  if( o_frame.empty() )  
   return 0;  

  resize(o_frame, showMat_r, Size(RWIDTH, RHEIGHT) );  
  Canny(showMat_r, showMat_r2, 50, 100);

  imshow("origin", showMat_r);  
  imshow("canny", showMat_r2);  

  //processing time
  ProccTimePrint(AAtime , "Total");     

  if( waitKey(5) > 0)  
   break;  

 }

 return 0;
}


void ProccTimePrint( unsigned long Atime , string msg)     
{     
 unsigned long Btime=0;     
 float sec, fps;     
 Btime = getTickCount();     
 sec = (Btime - Atime)/getTickFrequency();     
 fps = 1/sec;     
 printf("%s %.4lf(sec) / %.4lf(fps) \n", msg.c_str(),  sec, fps );     
}

///

gpu version code
#include < time.h>  
#include < opencv2\opencv.hpp>  
#include < opencv2\gpu\gpu.hpp>  
#include < string>  
#include < stdio.h>  


#ifdef _DEBUG          
#pragma comment(lib, "opencv_core249d.lib")  
#pragma comment(lib, "opencv_imgproc249d.lib")   //MAT processing  
#pragma comment(lib, "opencv_gpu249d.lib")  
#pragma comment(lib, "opencv_highgui249d.lib")  
#else  
#pragma comment(lib, "opencv_core249.lib")  
#pragma comment(lib, "opencv_imgproc249.lib")  
#pragma comment(lib, "opencv_gpu249.lib")  
#pragma comment(lib, "opencv_highgui249.lib")  
#endif     


#define RWIDTH 800  
#define RHEIGHT 600  

using namespace std;  
using namespace cv;  

void ProccTimePrint( unsigned long Atime , string msg);

int main()  
{  

 //input
 VideoCapture cap("C:\\videoSample\\tracking\\rouen_video.avi");

 //variable
 Mat o_frame;  
 Mat showMat_r;  
 Mat showMat_r2;  
 gpu::GpuMat o_frame_gpu;
 gpu::GpuMat r_frame_gpu;
 gpu::GpuMat rg_frame_gpu;
 gpu::GpuMat r_frame_gpu2;

 //first frame
 cap >> o_frame;  
 if( o_frame.empty() )  
  return 0;   


 unsigned long AAtime=0;

 while(1)  
 {  
  /////////////////////////////////////////////////////////////////////////  
  AAtime = getTickCount();  

  //frame
  cap >> o_frame;  
  if( o_frame.empty() )  
   return 0;  

  //upload to gpumat
  o_frame_gpu.upload(o_frame);  
  gpu::resize(o_frame_gpu, r_frame_gpu, Size(RWIDTH, RHEIGHT) );  
  gpu::cvtColor(r_frame_gpu, rg_frame_gpu, CV_BGR2GRAY);
  gpu::Canny(rg_frame_gpu, r_frame_gpu2, 50, 100); //gray only

  //download to mat
  r_frame_gpu.download(showMat_r);  
  r_frame_gpu2.download(showMat_r2);  

  
  //show image
  imshow("origin", showMat_r);  
  imshow("canny", showMat_r2);  

  //processing time
  ProccTimePrint(AAtime , "Total");     

  if( waitKey(10) > 0)  
   break;  

 }

 return 0;
}


void ProccTimePrint( unsigned long Atime , string msg)     
{     
 unsigned long Btime=0;     
 float sec, fps;     
 Btime = getTickCount();     
 sec = (Btime - Atime)/getTickFrequency();     
 fps = 1/sec;     
 printf("%s %.4lf(sec) / %.4lf(fps) \n", msg.c_str(),  sec, fps );     
}



Image Normalization using Standard deviation - example source code

You can understand Standard deviation normalization, referenced on this web page.
http://www.d.umn.edu/~deoka001/Normalization.html
This web page introduce that..(wrote by Siddharth Deokar)

-------------------------------------------------------------------------
Normalization by Standard Deviation
We normalize the attribute values by using standard deviation.

For Example:

Consider 5 instances which has attribute A with the follwing values: {-5, 6, 9, 2, 4}

First we calculate the mean as follows:

Mean = (-5+6+9+2+4) / 5 = 3.2

Second, we subtract the mean from all the values and square them:

(-5-3.2)^2 = 67.24
(6-3.2)^2 = 7.84
(9-3.2)^2 = 33.64
(2-3.2)^2 = 1.44
(4-3.2)^2 = 0.64

Then we find the deviation as follows:

Deviation = sqrt ((67.24 + 7.84 + 33.64 + 1.44 + 0.64) / 5) = 4.71

Now we normalize the attribute values:

x => (x - Mean) / Deviation

-5 => (-5 - 3.2) / 4.71 = -1.74
6 => (6 - 3.2) / 4.71 = 0.59
9 => (9 - 3.2) / 4.71 = 1.23
2 => (2 - 3.2) / 4.71 = -0.25
4 => (4 - 3.2) / 4.71 = 0.17

-------------------------------------------------------------------------



This is sample source code:

//

int i,j,z;
 double sum=0; 
 double Mean;
 
 //sum, mean
 for(j=0; j< Height; ++j)
 {
  for(i=0; i< Width; ++i)
  {
   sum = sum + Pdata[i][j];
  }
 }

 Mean = sum/(Height*Width);
 
 //Deviation
 double dSum=0;
 double deviation;
 double std_dev; 
 
 for(j=0; j< Height; ++j)
 {
  for(i=0; i< Width; ++i)
  {        
   Pdata[i][j] = (Pdata[i][j] - Mean);

   dSum = dSum + (Pdata[i][j]*Pdata[i][j]);
  }
 }
 
 deviation = dSum / (Width*Height);
 std_dev = sqrt(deviation);
 
 //Normalization
 for(j=0; j< Height; ++j)
 {
  for(i=0; i< Width; ++i)
  {        
   Pdata[i][j] = (Pdata[i][j] / std_dev);
  }
 }

YUV color format (444, 422, 411) - simple explanation

In the YUV color format, Y is bright information, U is blue color area, V is red color area.
Show the below picture. The picture is u-v color map

 
 
There are 3 type color format of YUV.
The types are 444, 422, 411.
 
 
444 is one pixel is 24 bits. 
 
 
 
 
422 is one pixel is 16 bits.
And U0, V0 is shared by Y0, Y1.



411 is one pixel is 12 bits.
 
 
 
 
This source code is convert code from YUV422 to RGB.
 

/ 


void ConvertYUV422toRGB(unsigned char** pSrc, unsigned char** pDst,int width,int height){
int i,j;
unsigned char* dst=*pDst;
unsigned char* src=*pSrc;
int Y1,Y2,U,V;
int R,G,B;

for(i=0;i2)
{
Y1=src[i*2+1];
Y2=src[i*2+3];
U=src[i*2];
V=src[i*2+2];

dst[i*3+2]=(unsigned char)((float)Y1+(1.4075f*(float)(V-128)));
dst[i*3+1]=(unsigned char)((float)Y1+(0.3455f*(float)(U-128)-(0.7169f*(float)(V-128))));
dst[i*3]=(unsigned char)((float)Y1+(1.7790f*(float)(U-128)));
dst[i*3+5]=(unsigned char)((float)Y2+(1.4075f*(float)(V-128)));
dst[i*3+4]=(unsigned char)((float)Y2+(0.3455f*(float)(U-128)-(0.7169f*(float)(V-128))));
dst[i*3+3]=(unsigned char)((float)Y2+(1.7790f*(float)(U-128)));
}
}

 


And YUV is converted by below fomulation.

R = Y + 1.4075(V-128)
G = Y - 0.3455(U-128) - 0.7169(V-128)
B = Y + 1.7790(U-128)
 
 
 
Thanks you.
 


sorry last source code is broken.
becasue html tag..
So I upload new version convert source code.
note!!! check Y position, the position is different as machine environment..
In the source code, stride means real width size.
YUV422 to RGB
--
//yuv to rgb
 int Y,U,V;   
 int R1,G1,B1;
 for(int ih=0; ihm_height; ++ih)
 {   
  //int iww=0;
  for(int iw=0; iwm_width; iw++)
  {
  
   if(iw %2 == 0)
   {
    Y = obj->m_yuv[ih*obj->m_stride + iw*2 + 0];
    U = obj->m_yuv[ih*obj->m_stride + iw*2 + 1];
    V = obj->m_yuv[ih*obj->m_stride + iw*2 + 3];
   }else{
    Y = obj->m_yuv[ih*obj->m_stride + iw*2 + 0];
    U = obj->m_yuv[ih*obj->m_stride + iw*2 -1];
    V = obj->m_yuv[ih*obj->m_stride + iw*2 + 1];
   }
   
   R1 = Y + 1.4075*(V-128);
   G1 = Y - 0.3455*(U-128) - 0.7169*(V-128);
   B1 = Y + 1.7790*(U-128);

   o_Image2.at(ih, iw)[0] = BYTE(MMIN(255, MMAX(0, B1)));// B1;
   o_Image2.at(ih, iw)[1] = BYTE(MMIN(255, MMAX(0, G1)));// G1;
   o_Image2.at(ih, iw)[2] = BYTE(MMIN(255, MMAX(0, R1)));// R1;
  }
 }
--
RGB to YUV422
--
int Y,U,V;   
   int R1,G1,B1;
   for(int ih=0; ih< obj->m_height; ++ih)
   {   
    //int iww=0;
    for(int iw=0; iw< obj->m_width; iw++)
    {

     B1 = o_Image2.at< cv::Vec3b>(ih, iw)[0];// B1;
     G1 = o_Image2.at< cv::Vec3b>(ih, iw)[1];// G1;
     R1 = o_Image2.at< cv::Vec3b>(ih, iw)[2];// R1;

     Y = (0.257*R1) + (0.504*G1) + (0.098*B1) +16;
     U = -(0.148*R1) - (0.291*G1) + (0.439*B1) + 128;
     V = (0.439*R1 ) - (0.368*G1) - (0.071*B1) + 128;
     Y = MMIN(255, MMAX(0, Y));
     U = MMIN(255, MMAX(0, U));
     V = MMIN(255, MMAX(0, V));

     if(iw %2 == 0)
     {
      obj->m_yuv[ih*obj->m_stride + iw*2 + 0] = Y;
      obj->m_yuv[ih*obj->m_stride + iw*2 + 1] = U;
      obj->m_yuv[ih*obj->m_stride + iw*2 + 3] = V;
     }else{
      obj->m_yuv[ih*obj->m_stride + iw*2 + 0] = Y;
      obj->m_yuv[ih*obj->m_stride + iw*2 -1] = U;
      obj->m_yuv[ih*obj->m_stride + iw*2 + 1] = V;
     }     
    }
--
 


Simple Image Processing Tool / C++ Source(MFC, OpenCV) / 간단한 영상처리 툴

Created Date : 2008.10
Language : C++(MFC)
Tool : Visual C++ 6.0
Library & Utilized : OpenCV 1.0
Reference :  Image Processing Book, Learning OpenCV
etc. : -



When I teach Image Processing to undergraduate students,  this program is made for practicing programming.
This code includes simple image processing method.

ex) Image adding, reverse, Lookup Table making, Gamma adjusting, Image Zoom in/out, Rotation, Morphology, Histogram Drawing, Stretching, Laplacian, sovel, RGB, HSI, YCbCr..

The code may be useful to beginner studying image processing , MFC and OpenCV.


<source code>



If you have good idea or advanced opinion, please reply me. Thank you

(Please understand my bad english ability. If you point out my mistake, I would correct pleasurably. Thank you!!)---------------------------------------------------------------------------



간단한 영상 처리 소스
RAW 를 오픈하여
2영상 더하기, 역상계산, 룩업데이블 생성, 감마 조절
영상 축소, 영상확대, 영상 회전
모폴로지, 히스트그램 그리기, 스트레칭, 평활화
라플라시안, 평화화 소벨
을 처리함
또한 BMP 파일을 오픈하여 RGB, HSI, Ycbcr로 채널을 분리한다.
그리고 OpenCV를 이용하여
영상 밝기 조절, 크기 조절, 회전, 이진화, 팽창, 수축, 필터를 적용해 본다.

압축 파일에 소스, 이미지, 간략한 설명 문서가 있음



<source code>



좋은 의견이나 답변 남겨 주세요.

Mini PhotoShop / Image Processing Tool / C++ source (MFC) / 미니 포토샵, 이미지 프로세싱 툴


Created Date : 2003.3
Language : C/C++
Tool : Microsoft Visual C++ 6.0 (MFC)
Library & Utilized : -
Reference :  Simplified approach to image prcessing book -Randy Crane-
etc. : Bmp Image Files







Many ages ago, when I studied image processing firstly, I made this program for training programming skill and studying  image processing.

This program include variety image processing functions.
For example

Filter function - blur,highpass, median, embossing, edge gaussian noise, morphology, the window that support preview function and the value of mask.
Geometry function - flip, rotation, zoom in/out
Channel split - RGB, HSI, CMYK, YIQ, YUW, YUV, YCbCr, the window that support preview function.
Color adjustment - Contrast, Brightness, HSI, Gamma, Red-Green tint, Reference, colorfulness
Histogram - binary, logarithm, auto contrast strech, end in contrast stretch.
etc - undo,redo function, skin color detection, labeling

You can download entire source code -> <Here>

Plz reply your opinion.
Thank you.

(Please understand my bad english ability. If you point out my mistake, I would correct pleasurably. Thank you!!)


-----------------------------------------------------


처음 영상처리 공부를 시작했을 때 프로그래밍과 이미지 처리 방법을 공부하기 위해 만든 프로그램 입니다.

이 프로그램은  bmp 파일포맷을 자유롭게 다룰수 있는 클래스를 제작하여 다음과 같은 여러가지 이미지 처리 기능을 구현했습니다.
필터기능 - blur,highpass, median, embossing, edge gaussian noise, morphology.
필터결과와 마스크값을 미리보기 기능창.
이미지조작 - 플립, 반전, 회전, 확대, 축소
체널 분리 - RGB, HSI, CMYK, YIQ, YUW, YUV, YCbCr, 분리된 채널을 한눈으로 볼수있는 기능창.
색조절 - Contrast, Brightness, HSI, Gamma, Red-Green tint, Reference, colorfulness.
히스토그램 - 이진화, logarithm, auto contrast strech,end in contrast stretch.
기타 - undo,redo기능 살색추출, 라벨링.

이 프로그램은 여기에서 받을 수 있습니다. <Here>

개선 사항이나 좋은 의견 있으시면 답변 주세요.
감사합니다.


Split color channels -> RGB, HSI, YCbCr, YUV, YIQ, YUW / C++ source / 칼라 채널 분리

Created Date : 2007.8
Language : C/C++
Tool : Microsoft Visual C++ 6.0 (MFC)
Library & Utilized : -
Reference : Simplified approach to image processing book -Randy Crane-
etc. : Bmp Image File
                                            RGB                                                   YCbCr


 
                                            YIQ                                                      YUV

                                             HSI                                                       YUW    

This program splits the channel into several version.
There are many color channels for image processing such as RGB, HSI, YCbCr, YUV, YIQ, YUW.
Each channels is made by specific formula that is introduced from many image processing books. The method of covert is simple and not difficult.

For example YCbCr is made by blow formula.
Y = 0.299*R + 0.587*G + 0.114*B
Cb = -0.16874*R + -0.33126*G + 0.5*B
Cr = 0.5*R + -0.41869*G - 0.08131*B

You can download entire source code and report document(doc) but the report is written by korean (sorry). -> <here>

If you have any question or opinion for improving, please reply.
Thank you.

(Please understand my bad english ability. If you point out my mistake, I would correct pleasurably. Thank you!!)
-------------------------------------

이 프로그램은 bmp파일을 열어서 여러가지 채널로 분리하는 간단한 영상 처리 프로그램입니다.
색 채널 분리는 이미지 처리 책에서 쉽게 그 방법과 원리를 찾아 볼 수 있습니다.
예를 들어 RGB에서 YCbCr로 분리하는 방법은 아래 수식으로 가능합니다.

Y = 0.299*R + 0.587*G + 0.114*B
Cb = -0.16874*R + -0.33126*G + 0.5*B
Cr = 0.5*R + -0.41869*G - 0.08131*B


더 자세한 내용은 링크한 저의 전체 소스 코드를 첨부하세요.
압축 파일에는 한글로 된 보고서도 포함되어 있습니다. - > <here>

오래 전에 만든 소스라 부족함이 많을 것 같네요.
문제점이나 개선 사항 있으면 답변 주세요.
감사합니다.