#include "stdafx.h" #include #include int mousex = 0; //x coordinate of mouse click int mousey = 0; //y coordinate of mouse click bool mouseClick = false; //Detect a click of the mouse int hueVal = 0; //Hue of pixel where mouse was clicked void mouse(int event, int x, int y, int flags, void* param) { switch(event) //Store the coordinates of the pixel that was clicked { case CV_EVENT_LBUTTONDOWN: { mousex = x; mousey = y; mouseClick = true; } break; } } IplImage* threshold(IplImage* img) { IplImage* hsvImg = cvCreateImage(cvGetSize(img), 8, 3); IplImage* threshImg = cvCreateImage(cvGetSize(img), 8, 1); //Convert image to HSV color space cvCvtColor(img, hsvImg, CV_BGR2HSV); cvShowImage("HSV", hsvImg); //Blur the HSV image to reduce the noise cvSmooth(hsvImg, hsvImg, CV_GAUSSIAN, 13, 13); cvSmooth(hsvImg, hsvImg, CV_GAUSSIAN, 13, 13); cvShowImage("HSV Blurred", hsvImg); cvSetMouseCallback("Video", mouse, (void*)hsvImg); //If the mouse was clicked get the Hue of that pixel if(mouseClick) { CvScalar pixelHSV; pixelHSV = cvGet2D(hsvImg, mousex, mousey); hueVal = (int)pixelHSV.val[0]; printf("Hue Value: %d\n", hueVal); mouseClick = false; } //Threshold the image by keeping only pixels in HSV range of the object selected cvInRangeS(hsvImg, cvScalar(hueVal - 10, 50, 50), cvScalar(hueVal + 10, 255, 255), threshImg); //Open then close the threshold image to remove unwanted objects IplConvKernel* element = cvCreateStructuringElementEx(10, 10, 1, 1, CV_SHAPE_ELLIPSE); cvErode(threshImg, threshImg, element, 2); cvDilate(threshImg, threshImg, element, 2); cvDilate(threshImg, threshImg, element, 2); cvErode(threshImg, threshImg, element, 2); cvReleaseImage(&hsvImg); return threshImg; } void drawRectangle(IplImage* img, IplImage* frame) { //Find the contours CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contours = 0; CvRect rect; CvPoint pt1, pt2; cvFindContours(img, storage, &contours); //Get two opposite corners of the contour to draw the rectangle if(contours) { rect = cvBoundingRect(contours, 0); pt1.x = rect.x+25; pt1.y = rect.y+25; pt2.x = rect.x+rect.width+25; pt2.y = rect.y+rect.height+25; cvRectangle(frame, pt1, pt2, CV_RGB(255,0,0), 2, 1, 0); } return; } int main() { //Initialize Webcam and begin capturing frames from camera CvCapture* capture = 0; capture = cvCaptureFromCAM(0); if(!capture) { printf("Could not initialize capturing...\n"); return -1; } while(true) { //Get frames from camera IplImage* frame = 0; frame = cvQueryFrame(capture); if(!frame) break; cvNamedWindow("Video"); //Get the threshold image IplImage* threshImg = threshold(frame); cvShowImage("Threshold", threshImg); //Draw rectangles around the colored object drawRectangle(threshImg, frame); cvShowImage("Video", frame); //If exit key is pressed, exit int c = cvWaitKey(20); if((char)c==27 ) { cvReleaseImage(&threshImg); break; } } cvReleaseCapture(&capture); return 0; }