[Python] i have working eye detection using OpenCV in python but can't manage to save those...

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have tried various eye recognition but so far only this one worked for me. But i need to export those eyes as image (.jpg). I have done similar code with faces but it will just not work with eyes. I have tried rewriting the face code, using global coordinates and even generated code with chat gpt and using its method.

    I just need to export those eyes to a jpg like in the code for faces

    code for eyes:

    import cv2

    eye = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

    cap = cv2.VideoCapture(0)

    while(cap.isOpened()):

    ret, frame = cap.read()

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

    eyes = eye.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5,minSize=(30, 30))

    for (x, y, w, h) in eyes:
    cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)

    cv2.imshow('Eye Recognition', frame)
    if cv2.waitKey(1) == ord('q'):
    break

    cap.release()
    cv2.destroyAllWindows()


    code for faces:

    import cv2

    face_classifier = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
    )
    video_capture = cv2.VideoCapture(0)

    def detect_bounding_box(vid):
    gray_image = cv2.cvtColor(vid, cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gray_image, 1.1, 5, minSize=(40, 40))
    for (x, y, w, h) in faces:
    cv2.rectangle(vid, (5*x, 5*y), (x + 2*w, y + 2*h),0,0)
    return faces

    while True:
    result, img = video_capture.read() # read frames from the video
    if result is False:
    break # terminate the loop if the frame is not read successfully

    faces = detect_bounding_box(
    img
    ) # apply the function we created to the video frame

    for (x,y,w,h) in faces:
    face = img[y:y+h, x:x+w] #slice the face from the image
    cv2.imwrite('Face.jpg', face) #save the image
    print('Image saved')


    if cv2.waitKey(100) & 0xFF == ord("q"):
    break

    video_capture.release()
    cv2.destroyAllWindows()

    Continue reading...

Compartilhe esta Página