At some point in image processing, you may want to see image edges on a live basis – for OCR, perhaps, or just because it looks kinda cool… Here’s an nifty little bit of C code (now somewhat deprecated) that will convert a live stream from a webcam to a black-and-white, edge-illuminated image.

#include <cv.h>
#include <highgui.h>
#include <stdio.h>

int main(){

int c, i, j;

//capture frame from camera
CvCapture* capture = cvCaptureFromCAM(CV_CAP_ANY);
fprintf(stderr, "Error: capture is NULL \n");
return -1;
//set resolution of capture
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 256);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 192);

//create window for display


//find/mark edges using canny
IplImage* frame = cvQueryFrame(capture);
IplImage* grey = cvCreateImage(cvGetSize(frame), 8, 1);
cvCvtColor(frame, grey, CV_RGB2GRAY);
IplImage* frame2 = cvCreateImage(cvSize(grey->width+6, grey->height+6), grey->depth, grey->nChannels);

CvPoint offset = cvPoint(3,3);
cvCopyMakeBorder(grey, frame2, offset, IPL_BORDER_REPLICATE, cvScalarAll(0));
IplImage* edges = cvCreateImage(cvGetSize(frame2), IPL_DEPTH_8U, frame2->nChannels);
cvCanny(frame2, edges, 4900, 39200, 7);

cvShowImage("canny", edges);

//wait for a keypress
int c = cvWaitKey(10);
if (c!=-1) break;

} //end while

cvReleaseCapture (&capture);
return 0;

} //end main

It’s a small window size (256×192) in this case because I was running it on the Raspberry Pi, and the Pi can’t handle a large window size – gets bogged down in the processing. Just reset those values to whatever your processor can handle.