{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# 引入影象處理庫OpenCV\n", "import cv2" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Image path\n", "imagePath = \"data/image/girl.jpg\"" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# Cascade path\n", "cascPath = \"data/haarcascades/haarcascade_frontalface_default.xml\"" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Create the haar cascade\n", "faceCascade = cv2.CascadeClassifier(cascPath)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Read the image\n", "image = cv2.imread(imagePath)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# Image to gray\n", "gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# Detect faces in the image\n", "faces = faceCascade.detectMultiScale(\n", " gray,\n", " scaleFactor=1.1, #表示在前後兩次相繼的掃描中,搜索窗口的比例係數。默認為1.1即每次搜索窗口依次擴大10%\n", " minNeighbors=5, #表示構成檢測目標的相鄰矩形的最小個數(默認為3個)\n", " minSize=(30, 30),#限制得到的目標區域的最小範圍\n", ")" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# Draw a rectangle around the faces\n", "for (x, y, w, h) in faces:\n", " cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "cv2.imshow(\"Face found\" ,image)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "cv2.waitKey(0)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "cv2.destroyAllWindows()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.6.8" } }, "nbformat": 4, "nbformat_minor": 2 }