{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of detected faces: 1\n", "face0.jpg is saved\n" ] } ], "source": [ "# import required libraries\n", "import cv2\n", "\n", "# read the input image\n", "img = cv2.imread('data/UAM-Andrzej-Wójtowicz.jpg')\n", "\n", "# convert to grayscale of each frames\n", "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n", "\n", "# read the haarcascade to detect the faces in an image\n", "face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')\n", "\n", "# detects faces in the input image\n", "faces = face_cascade.detectMultiScale(gray, 1.3, 4)\n", "print('Number of detected faces:', len(faces))\n", "\n", "# loop over all detected faces\n", "if len(faces) > 0:\n", " for i, (x, y, w, h) in enumerate(faces):\n", " # To draw a rectangle in a face\n", " cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255), 2)\n", " face = img[y:y + h, x:x + w]\n", " cv2.imshow(\"Cropped Face\", face)\n", " cv2.imwrite(f'face{i}.jpg', face)\n", " print(f\"face{i}.jpg is saved\")\n", " \n", "# display the image with detected faces\n", "cv2.imshow(\"image\", img)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3.10.8 64-bit", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.8" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "767d51c1340bd893661ea55ea3124f6de3c7a262a8b4abca0554b478b1e2ff90" } } }, "nbformat": 4, "nbformat_minor": 2 }