{"id":638,"date":"2011-06-11T02:29:18","date_gmt":"2011-06-11T01:29:18","guid":{"rendered":"http:\/\/julia2.lucaamore.com\/?p=638"},"modified":"2024-02-09T21:05:45","modified_gmt":"2024-02-09T19:05:45","slug":"computer-vision-opencv-face-detection-in-realtime-in-python","status":"publish","type":"post","link":"https:\/\/www.lucaamore.com\/?p=638","title":{"rendered":"Computer vision: OpenCV realtime face detection in Python"},"content":{"rendered":"\n<p>Per festeggiare degnamente l&#8217;arrivo del mio nuovo portatile in famiglia ho pensato di renderlo in grado di riconoscere volti umani da una sorgente video in tempo reale.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><a href=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2018\/01\/lukelv_futuristic_cyberpunk_computer_with_a_big_brain_ad_many_e_8dcaf38c-5d74-48d1-a399-1a02cad8f407.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2018\/01\/lukelv_futuristic_cyberpunk_computer_with_a_big_brain_ad_many_e_8dcaf38c-5d74-48d1-a399-1a02cad8f407-1024x1024.png\" alt=\"\" class=\"wp-image-1558\" srcset=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2018\/01\/lukelv_futuristic_cyberpunk_computer_with_a_big_brain_ad_many_e_8dcaf38c-5d74-48d1-a399-1a02cad8f407.png 1024w, https:\/\/www.lucaamore.com\/wp-content\/uploads\/2018\/01\/lukelv_futuristic_cyberpunk_computer_with_a_big_brain_ad_many_e_8dcaf38c-5d74-48d1-a399-1a02cad8f407-300x300.png 300w, https:\/\/www.lucaamore.com\/wp-content\/uploads\/2018\/01\/lukelv_futuristic_cyberpunk_computer_with_a_big_brain_ad_many_e_8dcaf38c-5d74-48d1-a399-1a02cad8f407-150x150.png 150w, https:\/\/www.lucaamore.com\/wp-content\/uploads\/2018\/01\/lukelv_futuristic_cyberpunk_computer_with_a_big_brain_ad_many_e_8dcaf38c-5d74-48d1-a399-1a02cad8f407-768x768.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure>\n\n\n\n<p><strong>Video dell&#8217;applicazione realizzata<\/strong><\/p>\n\n\n\n<p>Segue il video dimostrativo dell&#8217;applicazione realizzata:<\/p>\n\n\n<p><iframe loading=\"lazy\" title=\"OpenCV: realtime face detection in python\" width=\"584\" height=\"438\" src=\"https:\/\/www.youtube.com\/embed\/HTk_UwAYzVk?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n\n\n\n<p><strong>OpenCV (Open Source Computer Vision Library)<\/strong><\/p>\n\n\n\n<p>Era da tempo che desideravo utilizzare la libreria <a title=\"OpenCV\" href=\"http:\/\/opencv.org\">Open CV<\/a> per tornare a fare qualche esperimento di Computer Vision e per esplorare le sue tanto decantate potenzialit\u00e0.<\/p>\n\n\n\n<p>OpenCV \u00e8 una libreria rilasciata sotto licenza <a title=\"BSD-license\" href=\"http:\/\/opensource.org\/licenses\/bsd-license.php\">BSD<\/a> dalla Intel per l&#8217;elaborazione realtime delle immagini e la Computer Vision.<\/p>\n\n\n\n<p>Scritta in C e C++ \u00e8 utilizzabile, tramite wrapper (sia ufficiali che non) in diversi linguaggi: Python, Ruby, Java, C# ed \u00e8 stata portata sui principali sistemi operativi: GNU\/Linux, FreeBSD, Mac OS X, Windows ma anche Android e iOS per lo sviluppo di applicazioni su dispositivi mobili.<\/p>\n\n\n\n<p>Alcuni wrapper esportano solo un limitato sottoinsieme di funzionalit\u00e0.<\/p>\n\n\n\n<p>Mi sono reso conto che le potenzialit\u00e0 di tale libreria sono superiori alle mie pi\u00f9 rosee aspettative: c&#8217;\u00e8 tutto quello che pu\u00f2 servire (e si pu\u00f2 sognare) per realizzare applicazioni avanzate di Computer Vision ed elaborazione delle immagini.<\/p>\n\n\n\n<p><a title=\"Video di applicazioni possibili (Computer Vision)\" href=\"http:\/\/www.youtube.com\/playlist?p=PLFF718978F8808567\">Video di alcune interessanti applicazioni che \u00e8 possibile realizzare<\/a><\/p>\n\n\n\n<p>Sviluppare un&#8217;applicazione di ottima qualit\u00e0 per la face detection in realtime, problema normalmente complesso, diventa banale a tal punto che mi sono limitato a fare qualche ricerca su internet ed assemblare poche righe di codice Python trovate in alcuni blog.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2011\/06\/test-0009.jpg\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"484\" src=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2011\/06\/test-0009.jpg\" alt=\"face-detection demo 009\" class=\"wp-image-642\" srcset=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2011\/06\/test-0009.jpg 640w, https:\/\/www.lucaamore.com\/wp-content\/uploads\/2011\/06\/test-0009-300x226.jpg 300w\" sizes=\"auto, (max-width: 640px) 100vw, 640px\" \/><\/a><\/figure>\n\n\n\n<p><strong>Face Detection ed Haar-like features<\/strong><\/p>\n\n\n\n<p>L&#8217;algoritmo molto efficiente che viene utilizzato per la rilevazione dei volti, basato sulle Haar wavelet, \u00e8 stato elaborato da Viola-Jones nell&#8217;ambito dell&#8217;object detection ed \u00e8 stato pensato proprio per il problema della face detection in tempo reale.<\/p>\n\n\n\n<p>Con OpenCV \u00e8 possibile addestrare nuovi identificatori di oggetti tuttavia sono gi\u00e0 presenti i seguenti classificatori (in formato xml):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>haarcascade_eye.xml\nhaarcascade_frontalface_alt2.xml\nhaarcascade_frontalface_alt_tree.xml\nhaarcascade_frontalface_alt.xml\nhaarcascade_frontalface_default.xml\nhaarcascade_fullbody.xml\nhaarcascade_lefteye_2splits.xml\nhaarcascade_lowerbody.xml\nhaarcascade_mcs_eyepair_big.xml\nhaarcascade_mcs_eyepair_small.xml\nhaarcascade_mcs_lefteye.xml\nhaarcascade_mcs_mouth.xml\nhaarcascade_mcs_nose.xml\nhaarcascade_mcs_righteye.xml\nhaarcascade_mcs_upperbody.xml\nhaarcascade_profileface.xml\nhaarcascade_righteye_2splits.xml\nhaarcascade_upperbody.xml<\/code><\/pre>\n\n\n\n<p>Nelle mie prove, dopo aver individuato il volto, ho provato a rilevare anche gli occhi e la bocca ma in questo caso i risultati non mi hanno soddisfatto.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2011\/06\/test-0069.jpg\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"226\" src=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2011\/06\/test-0069-300x226.jpg\" alt=\"\" class=\"wp-image-678\" title=\"test-0069\" srcset=\"https:\/\/www.lucaamore.com\/wp-content\/uploads\/2011\/06\/test-0069-300x226.jpg 300w, https:\/\/www.lucaamore.com\/wp-content\/uploads\/2011\/06\/test-0069.jpg 640w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/figure>\n<\/div>\n\n\n<p><strong>Sorgente Python<br><\/strong><\/p>\n\n\n\n<p>I miei esperimenti sono stati effettuati su una macchina GNU\/Linux Ubuntu 11.04 con OpenCV 2.1.<\/p>\n\n\n\n<p>E&#8217; richiesto il pacchetto python-opencv, presente nei repository ufficiali e si assume che nel path dello script sia presente una directory haarcascades contenente i vari xml necessari per la detection.<\/p>\n\n\n\n<p>Su Ubuntu 11.04 \u00e8 possibile trovarli nella directory:<\/p>\n\n\n\n<p>\/usr\/share\/doc\/opencv-doc\/examples\/haarcascades\/haarcascades\/<\/p>\n\n\n\n<p>segue il codice sorgente utilizzato per la realizzazione del video:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: false; title: ; notranslate\" title=\"\">\n#!\/usr\/bin\/python\n\n#----------------------------------------------------------------------------\n# Face Detection Test (OpenCV)\n#\n# thanks to:\n# http:\/\/japskua.wordpress.com\/2010\/08\/04\/detecting-eyes-with-python-opencv\n#----------------------------------------------------------------------------\n\nimport cv\nimport time\nimport Image\n\ndef DetectFace(image, faceCascade):\n\n    min_size = (20,20)\n    image_scale = 2\n    haar_scale = 1.1\n    min_neighbors = 3\n    haar_flags = 0\n\n    # Allocate the temporary images\n    grayscale = cv.CreateImage((image.width, image.height), 8, 1)\n    smallImage = cv.CreateImage(\n            (\n                cv.Round(image.width \/ image_scale),\n                cv.Round(image.height \/ image_scale)\n            ), 8 ,1)\n\n    # Convert color input image to grayscale\n    cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)\n\n    # Scale input image for faster processing\n    cv.Resize(grayscale, smallImage, cv.CV_INTER_LINEAR)\n\n    # Equalize the histogram\n    cv.EqualizeHist(smallImage, smallImage)\n\n    # Detect the faces\n    faces = cv.HaarDetectObjects(\n            smallImage, faceCascade, cv.CreateMemStorage(0),\n            haar_scale, min_neighbors, haar_flags, min_size\n        )\n\n    # If faces are found\n    if faces:\n        for ((x, y, w, h), n) in faces:\n            # the input to cv.HaarDetectObjects was resized, so scale the\n            # bounding box of each face and convert it to two CvPoints\n            pt1 = (int(x * image_scale), int(y * image_scale))\n            pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))\n            cv.Rectangle(image, pt1, pt2, cv.RGB(255, 0, 0), 5, 8, 0)\n\n    return image\n\n#----------\n# M A I N\n#----------\n\ncapture = cv.CaptureFromCAM(0)\n#capture = cv.CaptureFromFile(\"test.avi\")\n\n#faceCascade = cv.Load(\"haarcascades\/haarcascade_frontalface_default.xml\")\n#faceCascade = cv.Load(\"haarcascades\/haarcascade_frontalface_alt2.xml\")\nfaceCascade = cv.Load(\"haarcascades\/haarcascade_frontalface_alt.xml\")\n#faceCascade = cv.Load(\"haarcascades\/haarcascade_frontalface_alt_tree.xml\")\n\nwhile (cv.WaitKey(15)==-1):\n    img = cv.QueryFrame(capture)\n    image = DetectFace(img, faceCascade)\n    cv.ShowImage(\"face detection test\", image)\n\ncv.ReleaseCapture(capture)\n\n<\/pre><\/div>","protected":false},"excerpt":{"rendered":"<p>Per festeggiare degnamente l&#8217;arrivo del mio nuovo portatile in famiglia ho pensato di renderlo in grado di riconoscere volti umani da una sorgente video in tempo reale. Video dell&#8217;applicazione realizzata Segue il video dimostrativo dell&#8217;applicazione realizzata: OpenCV (Open Source Computer &hellip; <a href=\"https:\/\/www.lucaamore.com\/?p=638\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":1645,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_sitemap_exclude":false,"_sitemap_priority":"","_sitemap_frequency":"","footnotes":""},"categories":[42,41,40,11,165],"tags":[79,78,77,65],"class_list":["post-638","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-computervision","category-facedetection","category-opencv","category-python","category-top","tag-computer-vision","tag-face-detection","tag-opencv","tag-python"],"_links":{"self":[{"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=\/wp\/v2\/posts\/638","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=638"}],"version-history":[{"count":108,"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=\/wp\/v2\/posts\/638\/revisions"}],"predecessor-version":[{"id":1716,"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=\/wp\/v2\/posts\/638\/revisions\/1716"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=\/wp\/v2\/media\/1645"}],"wp:attachment":[{"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=638"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=638"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.lucaamore.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=638"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}