Friday, July 2, 2021

Using Python, how to extract the biggest face from internet image and push this face to firebase storage

 


import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
def FirebaseStorage():
    dir = os.path.dirname(__file__)
    GOOGLE_APPLICATION_CREDENTIALS_file = os.path.join(dir, 'CREDENTIALS.json')
    print(GOOGLE_APPLICATION_CREDENTIALS_file)
    cred = credentials.Certificate(GOOGLE_APPLICATION_CREDENTIALS_file)
    firebase_admin.initialize_app(cred, {'storageBucket': 'xxxxBucketNamexxxxx.appspot.com' })
    return storage.bucket()

from datetime import datetime
def upload_2_FirebaseStorage(img_bytes):
    now = datetime.now()
    blob = FirebaseStorage().blob('profileIMG/'+now.strftime("%Y%m%d%H%M%S%f.jpg"))
	#use this for local image
    #blob.upload_from_filename(local_blob_path)
    blob.upload_from_string(img_bytes,content_type='image/jpeg')

    blob.make_public()
    return blob.public_url

import cv2
import urllib
import sys
import numpy as np
def ExtractUserIMG(IMG_URL):
    resp = urllib.request.urlopen(IMG_URL)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    #Use this for local images
    #imagePath = IMG_PATH
    #image = cv2.imread(imagePath)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.3,
        minNeighbors=3,
        minSize=(30, 30)
    )

    print("[INFO] Found {0} Faces.".format(len(faces)))
    
    max_area=0
    area=0
    for (x, y, w, h) in faces:
        area=h*w
        if area>max_area:
            max_area=area
            roi_color = image[y:y + h, x:x + w]
    print("[INFO] Object found. Saving locally.")
    #To save locally
    #cv2.imwrite('c:/images/Big_face.jpg', roi_color)
    img_bytes = cv2.imencode('.jpg', roi_color)[1].tobytes()
    return upload_2_FirebaseStorage(img_bytes) #image path on Firebase


ExtractUserIMG('https://www.quickanddirtytips.com/sites/default/files/styles/convert_webp_article_main_image/public/images/2332/people-persons-peoples.jpg')




Selected image by python script 












No comments: