סיכום סדנא - זיהוי פנים בפייתון

הי,

זה הקוד שכתבנו בסדנא עבור פיתרון התרגיל מכאן:
https://hackattic.com/challenges/basic_face_detection

מקווה שנהניתם. נתראה בסדנאות בהמשך.

import requests
import cv2
import sys

def init_image():
    r1 = requests.get('https://hackattic.com/challenges/basic_face_detection/problem?access_token=95acbd24a5cff4ca')
    r1.raise_for_status()
    info = r1.json()
    r2 = requests.get(info['image_url'])
    r2.raise_for_status()
    with open('faces.jpg', 'wb') as handle:
        for block in r2.iter_content(1024):
            handle.write(block)

classifier = cv2.CascadeClassifier('./data/haarcascade_frontalface_default.xml')
def is_face_in_square(square):
    res = classifier.detectMultiScale(square, scaleFactor=1.1, minNeighbors=5)
    # print(res)
    # cv2.imshow('Test Imag', square) 
    # cv2.waitKey(0) 
    # cv2.destroyAllWindows()
    return len(res) > 0

def squares():
    img = cv2.imread('faces.jpg')
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    (rows, cols) = gray_img.shape
    for i in range(rows // 100):
        for j in range(cols // 100):            
            sqr = gray_img[(i * 100):(i * 100)+100,(j * 100):(j * 100)+100]
            yield(sqr, i, j)

def submit_result(res):
    r = requests.post('https://hackattic.com/challenges/basic_face_detection/solve?access_token=95acbd24a5cff4ca&playground=1', json={
        'face_tiles': res
        })
    r.raise_for_status()
    print(r.text)


init_image()
# 64 squares! Yay!
res = [[i, j] for (sqr, i, j) in squares() if is_face_in_square(sqr)]
submit_result(res)