Error getting embeddings from a ROI using Deepface Deepface.represent

I am having issue with Deepface getting the embeddings from a cropped ROI identified by Retinaface.

I am trying to learn object recognition with my dataset(images) of a few celebrities to start with and may be thinking of using it for my personal photo library. I have tried Haar Cascade for face detection and LBPHFaceRecognize from open cv for face recognotion which was working good. Then i wanted to try Retinafce for face detection and to get a ROI. The ROI is stored in a list and using Deepface to get the embeddings from the selected ROI and store in another list. I am trying to store the embeddings to a list but I keep getting
raise ValueError(
ValueError: Face could not be detected in numpy array.Please confirm that the picture is a face photo or consider to set enforce_detection param to False.

Although all the images have a face which is been clearly detected. Here is my code for reference:

import os
import cv2 as cv
from retinaface import RetinaFace
from deepface import DeepFace
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score



artist =  ['50cent']   # type: ignore #MJ the GOAT!! , 'Kanye', 'Eminem', 'MichaelJackson'
ROOT_DIR = 'asset/Face_Recon_Dataset'     #Path to image dataset
faces_roi =[]
labels = []
embeddings = []
# now draw a rectangle on the face coordinates
# The facial range has :
# x1, y1) = (28, 51)  # top-left corner
# (x2, y2) = (61, 98)  # bottom-right corner
""" This defines the rectangular bounding box around the detected face.
- x1 (28): left edge of the face
- y1 (51): top edge of the face˜
- x2 (61): right edge of the face
- y2 (98): bottom edge of the face """



def get_roi():
    for artist_name in artist:
        # getting the index of the artist's name
        label = artist.index(artist_name)
        image_folder = os.path.join(ROOT_DIR,artist_name)    # getting to actual folder taht houss the images
        for artist_images in os.listdir(image_folder):       # listing all the images inside that directory
            image = os.path.join(image_folder,artist_images)
            resp = RetinaFace.detect_faces(image)
            # making sure a face exists
            if isinstance(resp,dict):
                img = cv.imread(image)
                for face_id, face_data in resp.items():
                    # print(face_id)
                    # print("x1: ", face_data['facial_area'][0])
                    # print("y1: ", face_data['facial_area'][1])
                    # print("x2: ", face_data['facial_area'][2])
                    # print("y2: ", face_data['facial_area'][3], "n")
                    # Reading image
                    
                    # detecting faces
                    x1 = face_data['facial_area'][0]
                    y1 = face_data['facial_area'][1]
                    x2 = face_data['facial_area'][2]
                    y2 = face_data['facial_area'][3]
                        
                    # Drawing a bounding box for the face 
                    # faces_rect = cv.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
                    face_roi = img[y1:y2,x1:x2]

                    # labelling the cropped roi faces with its name
                    faces_roi.append(face_roi)

                    labels.append(label)
    print(len(faces_roi))
    print(len(labels))
    print("Images lablled and indexed")
    print("Initializing Embedding process.....")
    get_embeddings()

def get_embeddings():
    """ Using deepface to extract embeddings from each facial roi """
    print("Satarting embedding: 🚀🚀 ")
    for roi in faces_roi:
        face_roi_resized = cv.resize(roi, (160, 160))  # Resize the face ROI to 160x160 pixels
        embedding = DeepFace.represent(face_roi_resized, model_name="Facenet")
        print(embedding)
        embeddings.append(embedding)
    print("Vectors stored in list..")


get_roi()

# Time to test and Train this bad boi using svm classifier
# labelling embedding and index to numpy array
X = np.array(embeddings)  #feature
y = np.array(labels)      #label

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train an SVM classifier
svm_model = SVC(kernel='linear')  # Linear kernel is a good default for embeddings
svm_model.fit(X_train, y_train)

# Evaluate the model
y_pred = svm_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"SVM Model accuracy: {accuracy * 100:.2f}%")


Could someone please help me understand why is that error so persistent even though there is a ROI that has been cropped and what would be the best way to tackle this error??

New contributor

Sanim Pokhrel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật