使用OpenCV开发机器视觉项目

来源:互联网 发布:炫佳网络 编辑:程序博客网 时间:2024/05/16 10:41

 

每过几天就去看看OpenCV.org的更新,今天突然发现了一个有趣的东西。http://opencv.org/mastering-opencv-with-practical-computer-vision-projects.html。弄opencv的人出版了一个Mastering OpenCV with Practical Computer Vision Projects的书,也就是用OpenCV开发的一切有意思的项目。


使用OpenCV开发机器视觉项目

 有以下9个章节

Chapters:

  • Ch1) Cartoonifier and Skin Changer for Android, by Shervin Emami.
  • Ch2) Marker-based Augmented Reality on iPhone or iPad, by Khvedchenia Ievgen.
  • Ch3) Marker-less Augmented Reality, by Khvedchenia Ievgen.
  • Ch4) Exploring Structure from Motion using OpenCV, by Roy Shilkrot.
  • Ch5) Number Plate Recognition using SVM and Neural Networks, by David Escrivá.
  • Ch6) Non-rigid Face Tracking, by Jason Saragih.
  • Ch7) 3D Head Pose Estimation using AAM and POSIT, by Daniel Lélis Baggio.
  • Ch8) Face Recognition using Eigenfaces or Fisherfaces, by Shervin Emami.
  • Ch9) Developing Fluid Wall using the Microsoft Kinect, by Naureen Mahmood.
  • Per-chapter Requirements:

    • Ch1: webcam (for desktop app), or Android development system (for Android app).
    • Ch2: iOS development system (to build an iOS app).
    • Ch3: OpenGL built into OpenCV.
    • Ch4: PCL (http://pointclouds.org/) and SSBA (http://www.inf.ethz.ch/personal/chzach/opensource.html).
    • Ch5: nothing.
    • Ch6: nothing, but requires training data for execution.
    • Ch7: nothing.
    • Ch8: webcam.
    • Ch9: Kinect depth sensor.

Screenshots:

  • Ch1) Cartoonifier and Skin Changer for Android: Ch1) Cartoonifier and Skin Changer for Android
  • Ch2) Marker-based Augmented Reality on iPhone or iPad: Ch2) Marker-based Augmented Reality on iPhone or iPad
  • Ch3) Marker-less Augmented Reality: Ch3) Marker-less Augmented Reality
  • Ch4) Exploring Structure from Motion using OpenCV: Ch4) Exploring Structure from Motion using OpenCV
  • Ch5) Number Plate Recognition using SVM and Neural Networks: Ch5) Number Plate Recognition using SVM and Neural Networks
  • Ch6) Non-rigid Face Tracking: Ch6) Non-rigid Face Tracking
  • Ch7) 3D Head Pose Estimation using AAM and POSIT: Ch7) 3D Head Pose Estimation using AAM and POSIT
  • Ch8) Face Recognition using Eigenfaces or Fisherfaces: Ch8) Face Recognition using Eigenfaces or Fisherfaces
  • Ch9) Developing Fluid Wall using the Microsoft Kinect: Ch9) Developing Fluid Wall using the Microsoft Kinect

     看看,他们确实涵盖了当今最热门的一些机器视觉相关项目,其中包括我喜欢的Kinect,甚至我熟悉的人脸识别、人脸跟踪、人脸朝向估计等等(这么多关于人脸的!),还包括虚拟现实之类技术,有时间也得看看。这本书可以买纸质版也可以买电子版,购买地址 PacktPub。好吧,估计一般人是买不到的,国外的书果然不便宜,$44.99

     不过书中配套的项目源码倒是都有的!https://github.com/MasteringOpenCV/code

     

第一个项目:卡通画和肤色变化初探

我在windows上尝试编译了第一个例子(他既有Android平台的代码也给出了PC平台的)。以下是截图:





    第一张和第四张图片都是卡通图,第2张是evil状态的,所以有点惨不忍睹吧,第三张是素描。具体算法我还未去细读,给出下载第一个项目的VS2010地址。通过debug可以编译出可用的exe,而release尽然无法检测到摄像头以致exe无法运行,编译时注意。

   给出主要的卡通画函数实现代码:

[cpp] view plaincopy
  1. /***************************************************************************** 
  2. *   cartoon.cpp 
  3. *   Create a cartoon-like or painting-like image filter. 
  4. ****************************************************************************** 
  5. *   by Shervin Emami, 5th Dec 2012 (shervin.emami@gmail.com) 
  6. *   http://www.shervinemami.info/ 
  7. ****************************************************************************** 
  8. *   Ch1 of the book "Mastering OpenCV with Practical Computer Vision Projects" 
  9. *   Copyright Packt Publishing 2012. 
  10. *   http://www.packtpub.com/cool-projects-with-opencv/book 
  11. *****************************************************************************/  
  12.   
  13. #include "cartoon.h"  
  14. #include "ImageUtils.h" // Handy functions for debugging OpenCV images, by Shervin Emami.  
  15.   
  16.   
  17.   
  18. // Convert the given photo into a cartoon-like or painting-like image.  
  19. // Set sketchMode to true if you want a line drawing instead of a painting.  
  20. // Set alienMode to true if you want alien skin instead of human.  
  21. // Set evilMode to true if you want an "evil" character instead of a "good" character.  
  22. // Set debugType to 1 to show where skin color is taken from, and 2 to show the skin mask in a new window (for desktop).  
  23. void cartoonifyImage(Mat srcColor, Mat dst, bool sketchMode, bool alienMode, bool evilMode, int debugType)  
  24. {  
  25.     // Convert from BGR color to Grayscale  
  26.     Mat srcGray;  
  27.     cvtColor(srcColor, srcGray, CV_BGR2GRAY);  
  28.   
  29.     // Remove the pixel noise with a good Median filter, before we start detecting edges.  
  30.     medianBlur(srcGray, srcGray, 7);  
  31.   
  32.     Size size = srcColor.size();  
  33.     Mat mask = Mat(size, CV_8U);  
  34.     Mat edges = Mat(size, CV_8U);  
  35.     if (!evilMode) {  
  36.         // Generate a nice edge mask, similar to a pencil line drawing.  
  37.         Laplacian(srcGray, edges, CV_8U, 5);  
  38.         threshold(edges, mask, 80, 255, THRESH_BINARY_INV);  
  39.         // Mobile cameras usually have lots of noise, so remove small  
  40.         // dots of black noise from the black & white edge mask.  
  41.         removePepperNoise(mask);  
  42.     }  
  43.     else {  
  44.         // Evil mode, making everything look like a scary bad guy.  
  45.         // (Where "srcGray" is the original grayscale image plus a medianBlur of size 7x7).  
  46.         Mat edges2;  
  47.         Scharr(srcGray, edges, CV_8U, 1, 0);  
  48.         Scharr(srcGray, edges2, CV_8U, 1, 0, -1);  
  49.         edges += edges2;  
  50.         threshold(edges, mask, 12, 255, THRESH_BINARY_INV);  
  51.         medianBlur(mask, mask, 3);  
  52.     }  
  53.     //imshow("edges", edges);  
  54.     //imshow("mask", mask);  
  55.   
  56.     // For sketch mode, we just need the mask!  
  57.     if (sketchMode) {  
  58.         // The output image has 3 channels, not a single channel.  
  59.         cvtColor(mask, dst, CV_GRAY2BGR);  
  60.         return;  
  61.     }  
  62.   
  63.     // Do the bilateral filtering at a shrunken scale, since it  
  64.     // runs so slowly but doesn't need full resolution for a good effect.  
  65.     Size smallSize;  
  66.     smallSize.width = size.width/2;  
  67.     smallSize.height = size.height/2;  
  68.     Mat smallImg = Mat(smallSize, CV_8UC3);  
  69.     resize(srcColor, smallImg, smallSize, 0,0, INTER_LINEAR);  
  70.   
  71.     // Perform many iterations of weak bilateral filtering, to enhance the edges  
  72.     // while blurring the flat regions, like a cartoon.  
  73.     Mat tmp = Mat(smallSize, CV_8UC3);  
  74.     int repetitions = 7;        // Repetitions for strong cartoon effect.  
  75.     for (int i=0; i<repetitions; i++) {  
  76.         int size = 9;           // Filter size. Has a large effect on speed.  
  77.         double sigmaColor = 9;  // Filter color strength.  
  78.         double sigmaSpace = 7;  // Positional strength. Effects speed.  
  79.         bilateralFilter(smallImg, tmp, size, sigmaColor, sigmaSpace);  
  80.         bilateralFilter(tmp, smallImg, size, sigmaColor, sigmaSpace);  
  81.     }  
  82.   
  83.     if (alienMode) {  
  84.         // Apply an "alien" filter, when given a shrunken image and the full-res edge mask.  
  85.         // Detects the color of the pixels in the middle of the image, then changes the color of that region to green.  
  86.         changeFacialSkinColor(smallImg, edges, debugType);  
  87.     }  
  88.   
  89.     // Go back to the original scale.  
  90.     resize(smallImg, srcColor, size, 0,0, INTER_LINEAR);  
  91.   
  92.     // Clear the output image to black, so that the cartoon line drawings will be black (ie: not drawn).  
  93.     memset((char*)dst.data, 0, dst.step * dst.rows);  
  94.   
  95.     // Use the blurry cartoon image, except for the strong edges that we will leave black.  
  96.     srcColor.copyTo(dst, mask);  
  97. }  
  98.   
  99.   
  100.   
  101. // Apply an "alien" filter, when given a shrunken BGR image and the full-res edge mask.  
  102. // Detects the color of the pixels in the middle of the image, then changes the color of that region to green.  
  103. void changeFacialSkinColor(Mat smallImgBGR, Mat bigEdges, int debugType)  
  104. {  
  105.         // Convert to Y'CrCb color-space, since it is better for skin detection and color adjustment.  
  106.         Mat yuv = Mat(smallImgBGR.size(), CV_8UC3);  
  107.         cvtColor(smallImgBGR, yuv, CV_BGR2YCrCb);  
  108.   
  109.         // The floodFill mask has to be 2 pixels wider and 2 pixels taller than the small image.  
  110.         // The edge mask is the full src image size, so we will shrink it to the small size,  
  111.         // storing into the floodFill mask data.  
  112.         int sw = smallImgBGR.cols;  
  113.         int sh = smallImgBGR.rows;  
  114.         Mat maskPlusBorder = Mat::zeros(sh+2, sw+2, CV_8U);  
  115.         Mat mask = maskPlusBorder(Rect(1,1,sw,sh));  // mask is a ROI in maskPlusBorder.  
  116.         resize(bigEdges, mask, smallImgBGR.size());  
  117.   
  118.         // Make the mask values just 0 or 255, to remove weak edges.  
  119.         threshold(mask, mask, 80, 255, THRESH_BINARY);  
  120.         // Connect the edges together, if there was a pixel gap between them.  
  121.         dilate(mask, mask, Mat());  
  122.         erode(mask, mask, Mat());  
  123.         //imshow("constraints for floodFill", mask);  
  124.   
  125.         // YCrCb Skin detector and color changer using multiple flood fills into a mask.  
  126.         // Apply flood fill on many points around the face, to cover different shades & colors of the face.  
  127.         // Note that these values are dependent on the face outline, drawn in drawFaceStickFigure().  
  128.         int const NUM_SKIN_POINTS = 6;  
  129.         Point skinPts[NUM_SKIN_POINTS];  
  130.         skinPts[0] = Point(sw/2,          sh/2 - sh/6);  
  131.         skinPts[1] = Point(sw/2 - sw/11,  sh/2 - sh/6);  
  132.         skinPts[2] = Point(sw/2 + sw/11,  sh/2 - sh/6);  
  133.         skinPts[3] = Point(sw/2,          sh/2 + sh/16);  
  134.         skinPts[4] = Point(sw/2 - sw/9,   sh/2 + sh/16);  
  135.         skinPts[5] = Point(sw/2 + sw/9,   sh/2 + sh/16);  
  136.         // Skin might be fairly dark, or slightly less colorful.  
  137.         // Skin might be very bright, or slightly more colorful but not much more blue.  
  138.         const int LOWER_Y = 60;  
  139.         const int UPPER_Y = 80;  
  140.         const int LOWER_Cr = 25;  
  141.         const int UPPER_Cr = 15;  
  142.         const int LOWER_Cb = 20;  
  143.         const int UPPER_Cb = 15;  
  144.         Scalar lowerDiff = Scalar(LOWER_Y, LOWER_Cr, LOWER_Cb);  
  145.         Scalar upperDiff = Scalar(UPPER_Y, UPPER_Cr, UPPER_Cb);  
  146.         // Instead of drawing into the "yuv" image, just draw 1's into the "maskPlusBorder" image, so we can apply it later.  
  147.         // The "maskPlusBorder" is initialized with the edges, because floodFill() will not go across non-zero mask pixels.  
  148.         Mat edgeMask = mask.clone();    // Keep an duplicate copy of the edge mask.  
  149.         for (int i=0; i<NUM_SKIN_POINTS; i++) {  
  150.             // Use the floodFill() mode that stores to an external mask, instead of the input image.  
  151.             const int flags = 4 | FLOODFILL_FIXED_RANGE | FLOODFILL_MASK_ONLY;  
  152.             floodFill(yuv, maskPlusBorder, skinPts[i], Scalar(), NULL, lowerDiff, upperDiff, flags);  
  153.             if (debugType >= 1)  
  154.                 circle(smallImgBGR, skinPts[i], 5, CV_RGB(0, 0, 255), 1, CV_AA);  
  155.         }  
  156.         if (debugType >= 2)  
  157.             imshow("flood mask", mask*120); // Draw the edges as white and the skin region as grey.  
  158.   
  159.         // After the flood fill, "mask" contains both edges and skin pixels, whereas  
  160.         // "edgeMask" just contains edges. So to get just the skin pixels, we can remove the edges from it.  
  161.         mask -= edgeMask;  
  162.         // "mask" now just contains 1's in the skin pixels and 0's for non-skin pixels.  
  163.   
  164.         // Change the color of the skin pixels in the given BGR image.  
  165.         int Red = 0;  
  166.         int Green = 70;  
  167.         int Blue = 0;  
  168.         add(smallImgBGR, Scalar(Blue, Green, Red), smallImgBGR, mask);  
  169. }  
  170.   
  171.   
  172. // Remove black dots (upto 4x4 in size) of noise from a pure black & white image.  
  173. // ie: The input image should be mostly white (255) and just contains some black (0) noise  
  174. // in addition to the black (0) edges.  
  175. void removePepperNoise(Mat &mask)  
  176. {  
  177.     // For simplicity, ignore the top & bottom row border.  
  178.     for (int y=2; y<mask.rows-2; y++) {  
  179.         // Get access to each of the 5 rows near this pixel.  
  180.         uchar *pThis = mask.ptr(y);  
  181.         uchar *pUp1 = mask.ptr(y-1);  
  182.         uchar *pUp2 = mask.ptr(y-2);  
  183.         uchar *pDown1 = mask.ptr(y+1);  
  184.         uchar *pDown2 = mask.ptr(y+2);  
  185.   
  186.         // For simplicity, ignore the left & right row border.  
  187.         pThis += 2;  
  188.         pUp1 += 2;  
  189.         pUp2 += 2;  
  190.         pDown1 += 2;  
  191.         pDown2 += 2;  
  192.         for (int x=2; x<mask.cols-2; x++) {  
  193.             uchar v = *pThis;   // Get the current pixel value (either 0 or 255).  
  194.             // If the current pixel is black, but all the pixels on the 2-pixel-radius-border are white  
  195.             // (ie: it is a small island of black pixels, surrounded by white), then delete that island.  
  196.             if (v == 0) {  
  197.                 bool allAbove = *(pUp2 - 2) && *(pUp2 - 1) && *(pUp2) && *(pUp2 + 1) && *(pUp2 + 2);  
  198.                 bool allLeft = *(pUp1 - 2) && *(pThis - 2) && *(pDown1 - 2);  
  199.                 bool allBelow = *(pDown2 - 2) && *(pDown2 - 1) && *(pDown2) && *(pDown2 + 1) && *(pDown2 + 2);  
  200.                 bool allRight = *(pUp1 + 2) && *(pThis + 2) && *(pDown1 + 2);  
  201.                 bool surroundings = allAbove && allLeft && allBelow && allRight;  
  202.                 if (surroundings == true) {  
  203.                     // Fill the whole 5x5 block as white. Since we know the 5x5 borders  
  204.                     // are already white, just need to fill the 3x3 inner region.  
  205.                     *(pUp1 - 1) = 255;  
  206.                     *(pUp1 + 0) = 255;  
  207.                     *(pUp1 + 1) = 255;  
  208.                     *(pThis - 1) = 255;  
  209.                     *(pThis + 0) = 255;  
  210.                     *(pThis + 1) = 255;  
  211.                     *(pDown1 - 1) = 255;  
  212.                     *(pDown1 + 0) = 255;  
  213.                     *(pDown1 + 1) = 255;  
  214.                 }  
  215.                 // Since we just covered the whole 5x5 block with white, we know the next 2 pixels  
  216.                 // won't be black, so skip the next 2 pixels on the right.  
  217.                 pThis += 2;  
  218.                 pUp1 += 2;  
  219.                 pUp2 += 2;  
  220.                 pDown1 += 2;  
  221.                 pDown2 += 2;  
  222.             }  
  223.             // Move to the next pixel.  
  224.             pThis++;  
  225.             pUp1++;  
  226.             pUp2++;  
  227.             pDown1++;  
  228.             pDown2++;  
  229.         }  
  230.     }  
  231. }  
  232.   
  233.   
  234. // Draw an anti-aliased face outline, so the user knows where to put their face.  
  235. // Note that the skin detector for "alien" mode uses points around the face based on the face  
  236. // dimensions shown by this function.  
  237. void drawFaceStickFigure(Mat dst)  
  238. {  
  239.     Size size = dst.size();  
  240.     int sw = size.width;  
  241.     int sh = size.height;  
  242.   
  243.     // Draw the face onto a color image with black background.  
  244.     Mat faceOutline = Mat::zeros(size, CV_8UC3);  
  245.     Scalar color = CV_RGB(255,255,0);   // Yellow  
  246.     int thickness = 4;  
  247.     // Use 70% of the screen height as the face height.  
  248.     int faceH = sh/2 * 70/100;  // "faceH" is actually half the face height (ie: radius of the ellipse).  
  249.     // Scale the width to be the same nice shape for any screen width (based on screen height).  
  250.     int faceW = faceH * 72/100; // Use a face with an aspect ratio of 0.72  
  251.     // Draw the face outline.  
  252.     ellipse(faceOutline, Point(sw/2, sh/2), Size(faceW, faceH), 0, 0, 360, color, thickness, CV_AA);  
  253.     // Draw the eye outlines, as 2 half ellipses.  
  254.     int eyeW = faceW * 23/100;  
  255.     int eyeH = faceH * 11/100;  
  256.     int eyeX = faceW * 48/100;  
  257.     int eyeY = faceH * 13/100;  
  258.     // Set the angle and shift for the eye half ellipses.  
  259.     int eyeA = 15; // angle in degrees.  
  260.     int eyeYshift = 11;  
  261.     // Draw the top of the right eye.  
  262.     ellipse(faceOutline, Point(sw/2 - eyeX, sh/2 - eyeY), Size(eyeW, eyeH), 0, 180+eyeA, 360-eyeA, color, thickness, CV_AA);  
  263.     // Draw the bottom of the right eye.  
  264.     ellipse(faceOutline, Point(sw/2 - eyeX, sh/2 - eyeY - eyeYshift), Size(eyeW, eyeH), 0, 0+eyeA, 180-eyeA, color, thickness, CV_AA);  
  265.     // Draw the top of the left eye.  
  266.     ellipse(faceOutline, Point(sw/2 + eyeX, sh/2 - eyeY), Size(eyeW, eyeH), 0, 180+eyeA, 360-eyeA, color, thickness, CV_AA);  
  267.     // Draw the bottom of the left eye.  
  268.     ellipse(faceOutline, Point(sw/2 + eyeX, sh/2 - eyeY - eyeYshift), Size(eyeW, eyeH), 0, 0+eyeA, 180-eyeA, color, thickness, CV_AA);  
  269.   
  270.     // Draw the bottom lip of the mouth.  
  271.     int mouthY = faceH * 53/100;  
  272.     int mouthW = faceW * 45/100;  
  273.     int mouthH = faceH * 6/100;  
  274.     ellipse(faceOutline, Point(sw/2, sh/2 + mouthY), Size(mouthW, mouthH), 0, 0, 180, color, thickness, CV_AA);  
  275.   
  276.     // Draw anti-aliased text.  
  277.     int fontFace = FONT_HERSHEY_COMPLEX;  
  278.     float fontScale = 1.0f;  
  279.     int fontThickness = 2;  
  280.     putText(faceOutline, "Put your face here", Point(sw * 23/100, sh * 10/100), fontFace, fontScale, color, fontThickness, CV_AA);  
  281.     //imshow("faceOutline", faceOutline);  
  282.   
  283.     // Overlay the outline with alpha blending.  
  284.     addWeighted(dst, 1.0, faceOutline, 0.7, 0, dst, CV_8UC3);  
原创粉丝点击