ads_header

Face Detection Using Python and OpenCV


Hello friend, in this post we will create a "Face Detection" program using the OpenCV library using the Python programming language. "Face Detection" is a program that can recognize a face in a frame, be it in the form of images or videos. One use of this technique is the attendance process carried out in an agency so that there is no forgery of attendance.





First, open your editor, here I use PyCharm then create a file named "index.py". When done, make sure you already have the file "haarcascade_frontalface_default.xml" if you don't have it, please download here and put it in the same folder as "index.py"

Open index.py and enter the following code

import cv2

faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

cam = cv2.VideoCapture(0)

First, we import the OpenCV library, then we load the haarcascade_frontalface_default.xml file into the "faceCascade" variable, then activate the camera loaded in the "cam" variable

Note : If you use an external camera, please change cv2.VideoCapture (0) to cv2.VideoCapture (1)

Next, enter the code below

while True:

    ret, im = cam.read()

    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(gray, 1.2,5)

The above code serves to do continuous looping on the code inside
  • Every frame taken using an external webcam or camera is entered into the variable "im"
  • Converting to Gray mode variable "im"
  • Detect all faces in the frame





Next, enter the following code

    for(x,y,w,h) in faces:

         cv2.rectangle(im, (x-20,y-20), (x+w+20, y+h+20), (0,255,0), 4)

    cv2.imshow('Face Detection', im)

The code above serves to make a green box in the face area that is detected in the frame. Then display in a new window with the name "Face Detection". When finished, enter the following closing code so that the window still appears.

    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cam.release()
cv2.destroyAllWindows()

At this point, the program is ready to run.

Full Source Code :


import cv2

faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

cam = cv2.VideoCapture(0)

while True:

    ret, im = cam.read()

    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(gray, 1.2,5)

    for(x,y,w,h) in faces:

        cv2.rectangle(im, (x-20,y-20), (x+w+20, y+h+20), (0,255,0), 4)

    cv2.imshow('Face Detection', im)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cam.release()
cv2.destroyAllWindows()


34 comments:

  1. Thank you so much for this blog...

    If you are looking for the best blockchain game development company. Do visit Webllisto, it is one of the best companies that provide smart contract development services, metaverse development services, Defi development services, Defi wallet development services, and internet marketing services for various industries. Visit the website - https://webllisto.com/

    ReplyDelete

  2. Value assignment help act as a tuition teacher and guides students looking for online academic assistance for assignments, homework, and essay writing services. contact valueassignmenthelp.com they provide plagiarism free content. Value assignment help is the best solution for you. They are best known for delivering assignment help services to students without having to break the bank. whatsapp no.: +91-9872003804, +61-413228507.

    ReplyDelete
  3. I find it useful is the ability to call Quickbooks phone numbers for help. This can be done by dialing Quickbooks Customer Service Support Phone Number +16023251557 When you do, you will reach the customer service team, who will be able to provide assistance with any question or issue that you may have.

    ReplyDelete
  4. I read your article and all the information in the article is very good and I am glad to read this useful information thank you for sharing the information.
    Quickbooks Payroll Support.+1 866-669-5068

    ReplyDelete
  5. When you or your company need help with QuickBooks or any other aspect of your business, dial Quickbooks Support Phone Number +1 888-210-4052.

    ReplyDelete
  6. Learn and discover classes on MS Office Computer Course and do practicals on Excel, Word, PowerPoint, Outlook. Path Creator designed an online Microsoft Course in Kolkata where you will get advanced training for MS- Excel and Learn MS Office in Kolkata. Our Course is designed to Learn to write documents, take notes, create spreadsheets, and more.

    Learn MS Office in Kolkata

    ReplyDelete
  7. Hi - Nice Article thanks for sharing with me.

    forex investor leads

    ReplyDelete
  8. Hey great post
    https://www.wamatechnology.com/top-ios-app-development-company-in-mumbai

    ReplyDelete
  9. If you are looking for contact information for QuickBooks, then be sure to give them a call at Quickbooks Customer Service +1 888-210-4052.

    ReplyDelete
  10. I read your blog its nice i like content its very useful for me
    I am Amara William I am always ready to learn new things and resolve problem regarding.
    I am a help you to resolve your quick book error, I am independent expert last 5 year to solve all error of quick book QuickBooks , working dedicatedly with the reliable QuickBooks support provider for resolving QuickBooks errors efficiently.


    https://www.qberrorsupport.com/convert-quickbooks-online-company-file-to-desktop/

    ReplyDelete
  11. QuickBooks is the most recommended and widely used accounting software which helps you get your work done easily and efficiently. This software comes with a customer service team that is active 24/7, so you can get answers for any sort of Quickbooks Customer Service question. You can contact them by dialling +1 615-510-6154.

    ReplyDelete
  12. Quickbooks is amazing software is used for small companies. if you are looking growth of their company then contact for any issue at
    QuickBooks Support Phone Number: +1 855-675-3194.

    ReplyDelete
  13. SAMI SARI LTD is specialized in manufacturing Made in Mongolia OEM/ODM cashmere products for brands and retailers. https://sari.mn

    ReplyDelete
  14. Such a informative blog it contains a good knowledge and help to understand things better also check out this International school in Faridabad

    ReplyDelete
  15. atakita adalah portal berita terkini menyajikan pristiwa peting dan terpercaya dalam hal informasi terupdate pristiwa pristiwa penting.https://katakita.id/wp-content/uploads/2022/05/KATA-KITA.png

    ReplyDelete
  16. Katakita atakita adalah portal berita terkini menyajikan pristiwa peting dan terpercaya dalam hal informasi terupdate pristiwa pristiwa penting. https://katakita.id/category/

    ReplyDelete
  17. Sildenafil Citrate for men is a prescription drug that helps men with erectile dysfunction by increasing blood flow to the penis. Sildenafil Citrate for men was approved by the FDA in 1998 and hit the market in March of 1999. Sildenafil Citrate for men works by inhibiting an enzyme called phosphodiesterase type 5 (PDE-5) which then increases the amount of nitric oxide produced in the body, hence increased blood flow to the penis. Sildenafil Citrate for men does not cure erectile dysfunction and is only used on an as-needed basis. https://propharmacystores.com/side-effects-of-sildenafil-citrate/

    ReplyDelete
  18. The estimation relies upon your disease, response to treatment, and various prescriptions you could take. Make sure to illuminate your PCP and medication expert concerning all of the things you use (counting specialist recommended drugs, nonprescription prescriptions, and normal things).Shakiness, headache, flushing, or stomach upset could occur. Vision changes, for instance, extended antipathy for light, clouded vision, or bother separating blue and green tones may similarly occur. If any of these effects last or disintegrate, tell your essential consideration doctor or medication expert in a flash. https://propharmacystores.com/sildenafil-coupons/

    ReplyDelete
  19. Natürlich sind Prognosen von der Bundesliga Analyse abhängig. Wie heimstark sind beide Mannschaften oder wie schneiden sie in den Pokalspielen ab? Die Analyse in der Wettszene wird auch als Mutter aller Statistiken bezeichnet. https://www.tipico.de/wett-tipps/bundesliga-prognose

    ReplyDelete
  20. Finding a well trusted supplier of legal highs chemicals may be extremely doubting today. FMT Medical Store opens doors to everyone who is in the market for substances and medications for scientific purposes. We provide an extensive catalog of research chemical which are known for purity.
    https://www.fmtmedicalstore.com/product/k2-liquid-spray/

    ReplyDelete
  21. เว็บพนันออนไลน์ที่ดีที่สุด UFABET อันดับ 1 เดิมพันขั้นต่ำ 10 บาท เว็บตรง แทงบอล บาคาร่า ปั่นสล็อต ครบทุกค่าย ระบบฝาก-ถอนออโต้ทำรายการเร็ว https://ufa356s.com/

    ReplyDelete
  22. We provide the best tuition and tutors in Lucknow,
    Tutoring for every section of students from all over
    India from Gomti Nagar, Kalidas Nagar, Madan Mohalla, and
    many more areas.Students will learn Maths, Science, English, etc.
    #tuitionsteachers.com

    ReplyDelete
  23. El pez piedra es probablemente uno de los peces más feos que existen, pero también es sumamente venenoso y peligroso sobre todo si tomamos en cuenta que pasa completamente desapercibido y se le confunde con una piedra común y corriente, cuando en realidad podría llegar a matar a un ser humano. https://esdepeces.com/

    ReplyDelete
  24. The Bitcoin (BTC) network is often praised for allowing users to transfer cryptocurrencies quickly and anonymously. However, transfers are made in exchange for a specific fee (called a fee). If you pay it too low, you may find that your bitcoin transaction is stuck. What then? In this text, we will explain how blockchain works and what to do in this case. https://btcaccelerators.com

    ReplyDelete
  25. The Bitcoin (BTC) network is often praised for allowing users to transfer cryptocurrencies quickly and anonymously. However, transfers are made in exchange for a bitcoin transaction accelerator
    specific fee (called a fee). btc accelerator If you pay it too low, you may find that your bitcoin transaction is stuck. What then? In this text, we will explain how blockchain works and what to do in this case.

    ReplyDelete
  26. helful,We provide the ..https://www.royalnextacademy.com/">Study MBBS in Abroad

    ReplyDelete
  27. دعاء السفر من أهم الأدعية المأثورة عن النبي صلى الله عليه وسلم والتي يرددها المسلم بكثرة يكاد يكون بشكل يومي، حيث قد يستمع إلى دعاء السفر صوت إذا ركب طائرة أو قد يكون دعاء السفر مكتوب قصير في أحد وسائل النقل أو يبحث المسافر عن دعاء السفر تويتر أو يكتب دعاء السفر كتابة على أحد وسائل التواصل الاجتماعي أو يردد دعاء السفر بالسيارة، فهو من الأدعية الهامة في حياة المسلم . دعاء السفر

    ReplyDelete
  28. Εάν ταξιδεύετε στις Ηνωμένες Πολιτείες για λιγότερο από 90 ημέρες και είστε πολίτης μιας χώρας που συμμετέχει στο Πρόγραμμα Απαλλαγής από την Βίζα, ενδέχεται να μην χρειάζεστε βίζα. esta visa για αμερικη

    ReplyDelete
  29. Welcome to a world where breathtaking views of Land, Sea, and Air glorifying nature’s beauty come together with the soothing melodies of Scott Huckabay’s masterful understanding of musical frequencies. Arrive with a desire for peaceful serenity and walk away with the ambition to Love All There Is.
    Please like, subscribe, and share to help support this new Scott Huckabay channel. Thank you!
    https://scotthuckabay.com

    ReplyDelete
  30. Das in unseren Verpackungen verwendete Material muss als Verpackungsmaterial für Lebensmittel zugelassen sein. Verpackungsmaterialien, die in direkten Kontakt mit dem Schnupftabak kommen, müssen gemäß etablierten Verfahren hergestellt und zu unseren Fabriken transportiert werden, um eine Kontamination zu vermeiden. Snus kaufen Schweiz

    ReplyDelete

  31. INGATBOLA88 merupakan situs penyedia jasa judi judi online #1 di Indonesia dengan memberikan beragam permainan seperti judi bola, slot online, poker online, dan casino online. sander hicks

    ReplyDelete
  32. إنشاء بريد إلكتروني جديد هو امر غاية في البساطة، رغم ذلك تختلف انواع البريد الإلكتروني لتعدد المنصات والطرق التي يمكنك من خلالها إنشاء بريد إلكتروني.

    ReplyDelete
  33. If you don’t have time to make a donation right away, you can also redeem your donation by sending it back in plastic wrap and mailing it back to the address provided on your receipt. The SalvationArmy will process your donation even if you don't receive an email notification after making your payment.

    ReplyDelete
  34. You can use a Bitcoin profit calculator to find out how much you'll get before your limit sell order starts or even before you start your limit sell order.
    https://www.evernote.com/shard/s626/sh/efe53e33-5e56-2873-611c-279f637e4674/3428e740dbcd8e5fa93c1d167fc1d176

    ReplyDelete

Powered by Blogger.