|
| 1 | +""" |
| 2 | +Haar Cascading Classifiers |
| 3 | +
|
| 4 | +Objective : Detect Object (Face) |
| 5 | +
|
| 6 | +Resources Haar Classifiers : |
| 7 | +https://www.analyticsvidhya.com/blog/2022/04/object-detection-using-haar-cascade-opencv/#:~:text=Haar%20cascade%20is%20an%20algorithm,%2C%20buildings%2C%20fruits%2C%20etc |
| 8 | +https://machinelearningmastery.com/using-haar-cascade-for-object-detection/ |
| 9 | +Resource for Haar classifiers: https://github.com/opencv/opencv/tree/master/data/haarcascades |
| 10 | +
|
| 11 | +Download photo from : |
| 12 | +https://unsplash.com/ |
| 13 | +
|
| 14 | +1. Open Colab and create new notebook. |
| 15 | +2. Download a free to download photo from unsplash or use one of your own. |
| 16 | +3. Upload the photo in the model |
| 17 | +4. Use haar classifier to detect face in image |
| 18 | +""" |
| 19 | + |
| 20 | +from google.colab.patches import cv2_imshow #to assist with image processing and showing |
| 21 | +import cv2 |
| 22 | +import numpy as np |
| 23 | + |
| 24 | + |
| 25 | +# Defining the list of image URLs from Unsplash |
| 26 | +foto = [ |
| 27 | + "https://spash.com/[chosen photo URL]" |
| 28 | + "https://splash.com/[chosen photo URL]" |
| 29 | +] |
| 30 | + |
| 31 | +def load_image_from_url(url): |
| 32 | + resp = urlopen(url) |
| 33 | + image = np.asarray(bytearray(resp.read()), dtype="uint8") |
| 34 | + image = cv2.imdecode(image, cv2.IMREAD_COLOR) |
| 35 | + return image |
| 36 | + |
| 37 | +for i, image_url in enumerate(foto): |
| 38 | + img = load_image_from_url(image_url) |
| 39 | + print(f"Displaying image {i+1}") |
| 40 | + cv2_imshow(img) |
| 41 | +#The above code should be in one cell and display the photo you chose. |
| 42 | + |
| 43 | +###########next cell############## |
| 44 | + |
| 45 | +# Loading the pre-trained Haar cascade for face detection |
| 46 | +face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') #you can use others but this one is used the most. Resource link above. |
| 47 | + |
| 48 | +#detecting the face and covert to grayscale |
| 49 | +def detect_faces(image): |
| 50 | + gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
| 51 | + faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=20, minSize=(20,20)) #Setting general parameters. Resouces above to understand more. |
| 52 | + for (x, y, w, h) in faces: |
| 53 | + cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2) #blue colour bounding box |
| 54 | + return image |
| 55 | + |
| 56 | + |
| 57 | +# Processing each loaded and resized image with Haar cascade |
| 58 | +for i, url in enumerate(foto, start=1): |
| 59 | + img=load_image_from_url(url) |
| 60 | + img_with_faces = detect_faces(img.copy()) |
| 61 | + print(f"Detecting Face {i}") |
| 62 | + cv2_imshow(img_with_faces) #face |
| 63 | + |
| 64 | +#this should display the image with a blue bounding box. |
| 65 | + |
| 66 | + |
| 67 | + |
| 68 | + |
0 commit comments