2013年10月3日 星期四

【OpenCV】利用膚色加輪廓擷取手部區域 Extract hand region using skin and contour detection

  1. 使用膚色偵測篩選可能為手的區域
  2. 將影像二值化
  3. 進行輪廓偵測
  4. 判斷輪廓最小長方形區域


Exported from Notepad++
#include "stdafx.h" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <ctype.h> using namespace cv; using namespace std; void contourFilter(Mat image, Mat skin_img) { RNG rng(12345); Mat threshold_img; vector<vector<Point> > contours; vector<Vec4i> hierarchy; threshold( skin_img, threshold_img, 125, 255, THRESH_BINARY ); //將skin_img二值化 findContours( threshold_img, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); //在threshold_img影像中尋找所有的輪廓 vector<vector<Point> > contours_poly( contours.size() ); vector<Rect> boundRect( contours.size() ); for( int i = 0; i < contours.size(); i++ ) { approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true ); //計算可以包含輪廓的最小長方形區域 boundRect[i] = boundingRect( Mat(contours_poly[i]) ); Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); //隨機給一個顏色 if(boundRect[i].area() > 900) {//長方形區域面積超過900,則畫在影像上 drawContours( image, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point() ); rectangle( image, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 ); } } namedWindow( "Contours", CV_WINDOW_AUTOSIZE ); imshow( "Contours", image ); } int main( int argc, char** argv ) { VideoCapture cap; cap.open(1);; namedWindow( "OpenCV Demo", 1 ); Mat image; Mat hsvImg, skinImg, resizeImg; for(;;) { Mat frame; cap >> frame; if( frame.empty() ) break; cv::resize(frame, resizeImg, cv::Size(320, 240)); resizeImg.copyTo(image); cvtColor( image, hsvImg, CV_BGR2HSV ); inRange(hsvImg, Scalar(0, 58, 20), Scalar(50, 173, 230), skinImg); //篩選hsvImg在HSV顏色空間屬於膚色的區域 cv::dilate(skinImg, skinImg, Mat(), Point( -1 , -1 ), 3 ); //對skinImg進行膨脹 cv::erode(skinImg, skinImg, Mat(), Point( -1 , -1 ), 3 ); //對skinImg進行侵蝕 contourFilter(image, skinImg); imshow("OpenCV Demo", skinImg); waitKey(10); } return 0; }




相關資訊:OpenCV學習日記

0 意見:

張貼留言