# -*- coding: utf-8 -*- """ Created on Wed Oct 16 14:13:46 2019 @author: inkuml05 """ import cv2 import numpy as np face_classifier = cv2.CascadeClassifier( 'C:/Users/inkuml05/Downloads/opencv-master/opencv-master/data/haarcascades/haarcascade_frontalface_default.xml' ) ##creating a method to extract the face features and return the data def face_extractor(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) face = face_classifier.detectMultiScale(gray, 1.3, 5) if face is (): return None for (x, y, w, h) in face: cropped_faces = img[y:y + h, x:x + w] return cropped_faces cap = cv2.VideoCapture(0) count = 0 ## Run the camera and capture. while True:
break cv2.destroyAllWindows() cap.release() if __name__ == "__main__": main() import numpy as np import os import cv2 face_cascade = cv2.CascadeClassifier( 'F:\\opencv\\opencv-master\\data\\haarcascades\\haarcascade_frontalface_default.xml' ) cap = cv2.VideoCapture(0) path = "C:\Users\Tanvee\Desktop\ForskML\Day27" # path were u want store the data set id = input('enter user name') try: # Create target Directory os.mkdir(path + str(id)) print("Directory ", path + str(id), " Created ") except FileExistsError: print("Directory ", path + str(id), " already exists") sampleN = 0
from random import randint import cv2 import sys import os import traceback import pandas as pd import numpy as np from natsort import natsorted import glob import numpy as np import cv2 as cv # 얼굴과 눈을 검출하기 위해 미리 학습시켜 놓은 XML 포맷으로 저장된 분류기를 로드 face_cascade = cv.CascadeClassifier('haarcascade_frontface.xml') # 얼굴과 눈을 검출할 그레이스케일 이미지를 준비 image_path = glob.glob( 'C:/Users/mmclab1/Desktop/AI training data set/data/video_2images/*.*', recursive=False) image_path = natsorted( image_path ) #'C:/Users/mmclab1/Desktop/AI training data set/data/video_2images\\id32_id35_0002_frame-2.jpg' for path in image_path: img = cv.imread(path) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # 이미지에서 얼굴을 검출 faces = face_cascade.detectMultiScale(gray, 1.3, 5)
import cv2 as cv import time import random import string face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml') smile_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_smile.xml') cap = cv.VideoCapture(0) if not cap.isOpened(): print("无法打开摄像头") exit() while (True): ret, frame = cap.read() if not ret: print("无法获取画面帧") break faces = face_cascade.detectMultiScale(frame, 1.3, 2) img = frame flag = False for (x, y, w, h) in faces: face_area = img[y:y + h, x:x + w] smiles = smile_cascade.detectMultiScale(face_area, scaleFactor=1.16,
import cv2 import os from keras.models import load_model import numpy as np from pygame import mixer import time mixer.init() sound = mixer.Sound('alarm.wav') face = cv2.CascadeClassifier('cascade_files\haarcascade_frontalface_alt.xml') leye = cv2.CascadeClassifier('cascade_files\haarcascade_lefteye_2splits.xml') reye = cv2.CascadeClassifier('cascade_files\haarcascade_righteye_2splits.xml') lbl = ['Close', 'Open'] model = load_model('models/cnncat2.h5') path = os.getcwd() cap = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_COMPLEX_SMALL count = 0 score = 0 thicc = 2 rpred = [99] lpred = [99] while (True): ret, frame = cap.read() height, width = frame.shape[:2] gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
''' github.com/razyar khoderazyar.ir ''' import cv2 import sys imagePath = sys.argv[1] cascPath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30) #flags = cv2.CV_HAAR_SCALE_IMAGE ) print(" i found {0} faces! in this pic".format(len(faces)))
from constants import * import cv2 import pandas as pd import numpy as np from PIL import Image cascade_classifier = cv2.CascadeClassifier(CASC_PATH) def format_image(image): if len(image.shape) > 2 and image.shape[2] == 3: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: image = cv2.imdecode(image, cv2.CV_LOAD_IMAGE_GRAYSCALE) gray_border = np.zeros((150, 150), np.uint8) gray_border[:, :] = 200 gray_border[((150 / 2) - (SIZE_FACE / 2)):((150 / 2) + (SIZE_FACE / 2)), ((150 / 2) - (SIZE_FACE / 2)):((150 / 2) + (SIZE_FACE / 2))] = image image = gray_border faces = cascade_classifier.detectMultiScale(image, scaleFactor=1.3, minNeighbors=5) # None is we don't found an image if not len(faces) > 0: #print "No hay caras" return None max_area_face = faces[0] for face in faces: if face[2] * face[3] > max_area_face[2] * max_area_face[3]:
import cv2 import dlib import time import threading import math # Haarcascade classifier to identify vehicles carCascade = cv2.CascadeClassifier('myhaar.xml') video = cv2.VideoCapture('4.mp4') #video WIDTH = 1280 HEIGHT = 720 #define points to calculate speed def estimateSpeed(location1, location2): #calculating pixels between two points d_pixels = math.sqrt(math.pow(location2[0] - location1[0], 2) + math.pow(location2[1] - location1[1], 2)) # ppm = location2[2] / carWidht ppm = 8.8 #pixels per metre d_meters = d_pixels / ppm #distance in metres #print("d_pixels=" + str(d_pixels), "d_meters=" + str(d_meters)) fps = 18 #frames per second speed = d_meters * fps * 3.6 return speed def trackMultipleObjects(): rectangleColor = (0, 255, 0) frameCounter = 0 currentCarID = 0 fps = 0
import cv2 import serial import time fire_cascade = cv2.CascadeClassifier('fire_detection.xml') ser = serial.Serial( 'COM3', 9600) #change COM port number on which your arduino is connected cap = cv2.VideoCapture( 0) #0 in case of inbuilt web cam and 1 if external cam is used if cap.isOpened(): while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) fire = fire_cascade.detectMultiScale(img, 1.2, 5) for (x, y, w, h) in fire: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = img[y:y + h, x:x + w] print('Fire is detected..!') ser.write('p'.encode()) time.sleep(0.2) cv2.imshow('img', img) print('Continue Capturing Video...') ser.write('s'.encode()) k = cv2.waitKey(30) & 0xff if k == 27: break cap.release()
from os import listdir from os.path import isfile, join # 테스트 이미지 불러오기 mypath='./image/' path = './data/haarcascades' onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] for i in onlyfiles: image = cv2.imread('./image/'+i) # RGB -> Gray로 변환 # 얼굴 찾기 위해 그레이스케일로 학습되어 있기때문에 맞춰줘야 한다. image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 정면 얼굴 인식용 cascade xml 불러오기 # 그 외에도 다양한 학습된 xml이 있으니 테스트해보면 좋을듯.. face_cascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_frontalface_default.xml') # 이미지내에서 얼굴 검출 faces = face_cascade.detectMultiScale(image_gray, 1.3, 5) # 얼굴 검출되었다면 좌표 정보를 리턴받는데, 없으면 오류를 뿜을 수 있음. for (x,y,w,h) in faces: cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2) # 원본 영상에 위치 표시 roi_gray = image_gray[y:y+h, x:x+w] # roi 생성 roi_color = image[y:y+h, x:x+w] # roi cv2.imshow('img',image) # 이미지 띄우기 cv2.waitKey(0) cv2.destroyAllWindows() # 윈도우 종료
import cv2 import numpy as np # Haar Cascade face_cascade = cv2.CascadeClassifier( 'haar_cascade_files/haarcascade_frontalface_default.xml') if face_cascade.empty(): raise IOError('Unable to load face cascade classifier xml file') # Video capturing and scaling cap = cv2.VideoCapture(0) scaling_factor = 0.5 #Capture frame while True: _, frame = cap.read() #Resize frame frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA) #Image to grayscale conversion gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #Running face detecor on gray image face_rects = face_cascde.detectMultiScale(gray, 1.3, 5)
def remote(url, names): file1 = open("admin_files/logs.txt", "a+") file2 = open("admin_files/mobile_no.txt", "r") data = file2.read() file2.close() recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read('trainer.yml') cascadePath = 'haarcascade_frontalface_default.xml' faceCascade = cv2.CascadeClassifier(cascadePath) font = cv2.FONT_HERSHEY_SIMPLEX id = 0 #Variable to counter valid and invalid valid = 0 invalid = 0 flag = 0 while (flag == 0): site = requests.get(url) img_arr = np.array(bytearray(site.content), dtype=np.uint8) img = cv2.imdecode(img_arr, -1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(10, 10)) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2) id, confidence = recognizer.predict(gray[y:y + h, x:x + w]) text = "" if (confidence < 48): valid += 1 text = names[id] if (valid >= 60): cv2.putText(img, str("Logged to system"), (x + 5, y - 5), font, 1, (255, 255, 255), 2) cv2.putText(img, str("Paused for few minutes.."), (x + 5, y + 5 + 270), font, 1, (255, 255, 255), 2) cv2.imshow('camera', img) if cv2.waitKey(1) & 0xFF == ord('q'): flag = 1 break x = datetime.datetime.now() x = x.strftime("%m/%d/%Y, %H:%M:%S") msg = "\n " + text + " logged at " + x file1.write(msg) valid = 0 invalid = 0 time.sleep(3) else: cv2.putText(img, str("Detected " + text), (x + 5, y - 5), font, 1, (255, 255, 255), 2) cv2.imshow('camera', img) if cv2.waitKey(1) & 0xFF == ord('q'): flag = 1 break else: invalid += 1 if (invalid >= 150): cv2.putText( img, str("Cannot detect the face system will be alerted.."), (x + 5, y - 5), font, 1, (255, 255, 255), 2) cv2.imshow('camera', img) if cv2.waitKey(1) & 0xFF == ord('q'): flag = 1 break alerts.alert(data) invalid = 0 valid = 0 else: cv2.putText(img, str("Detecting.."), (x + 5, y - 5), font, 1, (255, 255, 255), 2) cv2.imshow('camera', img) if cv2.waitKey(1) & 0xFF == ord('q'): flag = 1 break cv2.imshow('camera', img) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.release() cv2.destroyAllWindows() file1.close()
from flask import Flask, render_template, Response import cv2 face_cascade = cv2.CascadeClassifier('haarcascade.xml') app = Flask(__name__) camera = cv2.VideoCapture(0) def gen_frames(): while True: success, img = camera.read() if not success: break else: img = img gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = img[y:y + h, x:x + w] ret, buffer = cv2.imencode('.jpg', img) frame = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n' ) # concat frame one by one and show result
cap = cv2.VideoCapture(0) # Create the haar cascade cascades = [ '/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml', 'haarcascade_frontalface_default.xml', ] if hasattr(cv2, 'data'): cascades.insert(0, os.path.join(cv2.data.haarcascades, 'haarcascade_frontalface_default.xml')) for path in cascades: if os.path.isfile(path): print('Loading face model:', path) faceCascade = cv2.CascadeClassifier(path) break else: print('No haarcascade_frontalface_default.xml found.') print('Try:\nsudo apt install opencv-data\nor:') print('wget https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml') exit() def face_area(rect): "Ugly hack, because Py3 can't unpack tuples in lambda." x, y, w, h = rect del x, y return w * h
import numpy as np import cv2 faceCascade = cv2.CascadeClassifier('/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_default.xml') smileCascade = cv2.CascadeClassifier('/usr/local/share/opencv4/haarcascades/haarcascade_smile.xml') cap = cv2.VideoCapture(0) cap.set(3,640) # set Width cap.set(4,480) # set Height while (True): # ret : frame capture (boolean) # img : Capture frame ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow("video", img) #detect faces in the image faces = faceCascade.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=5, minSize=(20,20), ) for(x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) roi_gray = gray[y:y+h, x:x+w]
''' Created on 19 feb. 2018 @author: Andres @info: https://cucopc.es/2016/06/09/raspberry-pi-reconocimiento-facial-opencv/ ''' #Ejemplo de deteccion facial con OpenCV y Python #Por Glare #www.robologs.net import numpy as np import cv2 #cargamos la plantilla e inicializamos la webcam: face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') cap = cv2.VideoCapture(0) while (True): #leemos un frame y lo guardamos ret, img = cap.read() #convertimos la imagen a blanco y negro gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #buscamos las coordenadas de los rostros (si los hay) y #guardamos su posicion faces = face_cascade.detectMultiScale(gray, 1.3, 5) #Dibujamos un rectangulo en las coordenadas de cada rostro for (x, y, w, h) in faces:
import cv2 arquivo = 'haarcascade_frontalface_default.xml' faceCascade = cv2.CascadeClassifier(arquivo) captura = cv2.VideoCapture(0) while True: s, imagem = captura.read() imagem = cv2.flip(imagem, 180) faces = faceCascade.detectMultiScale(imagem, minNeighbors=5, minSize=(30, 30), maxSize=(200, 200)) for (x, y, w, h) in faces: cv2.rectangle(imagem, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("Video", imagem) if cv2.waitKey(1) & 0xFF == ord('q'): break captura.release() cv2.destroyAllWindows()
def _build_face_cascade(self): full_path = os.path.join(os.path.dirname(__file__), 'opencv', 'haarcascade_frontalface_default.xml') return cv2.CascadeClassifier(full_path)
import numpy as np import cv2 face_cascade = cv2.CascadeClassifier( 'D:\\My_study\\haarcascade_frontalface_default.xml' ) # replace the path of the xml file cap = cv2.VideoCapture(0) while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: print(x, y, w, h) cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = img[y:y + h, x:x + w] cv2.imshow('img', img) if cv2.waitKey(1) & 0xFF == ord(' '): break cap.release() cv2.destroyAllWindows()
import cv2 import math import os import tarfile import numpy as np import tensorflow as tf IMAGES_DOWNLOAD_URL = 'http://tamaraberg.com/faceDataset/originalPics.tar.gz' ANNOTATIONS_DOWNLOAD_URL = 'http://vis-www.cs.umass.edu/fddb/FDDB-folds.tgz' DIRECTORY = os.path.join(os.path.dirname(__file__), 'fddb') # CASCADES_DIR = os.path.normpath(os.path.join(cv2.__file__, '..', '..', '..', '..', 'share', 'OpenCV', 'haarcascades')) CASCADES_DIR = "/usr/local/opt/opencv/share/OpenCV/haarcascades" FACE_CASCADE = cv2.CascadeClassifier( os.path.join(CASCADES_DIR, 'haarcascade_frontalface_default.xml')) EYES_CASCADE = cv2.CascadeClassifier( os.path.join(CASCADES_DIR, 'haarcascade_eye.xml')) EXCLUDES = set([ '2002/07/19/big/img_445', '2002/07/21/big/img_76', '2002/07/22/big/img_152', '2002/07/26/big/img_513', '2002/07/29/big/img_136', '2002/07/31/big/img_898', '2002/08/05/big/img_3591', '2002/08/07/big/img_1576', '2002/08/16/big/img_81', '2002/08/16/big/img_1055', '2002/08/18/big/img_293',
if imgArray[x].shape[:2] == imgArray[0].shape[:2]: imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale) else: imgArray[x] = cv2.resize( imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None, scale, scale) if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR) hor = np.hstack(imgArray) ver = hor return ver # LOAD THE CLASSIFIERS cascade = cv2.CascadeClassifier(facecascadelocation) faces1 = cascade.detectMultiScale(img1) faces2 = cascade.detectMultiScale(img2) # ADD TRACKBARS while True: # DISPLAY THE DETECTED OBJECTS for (x, y, w, h) in faces1: cv2.rectangle(img1, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(img1, "Face!", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 0), 2) roi_color = img1[y:y + h, x:x + w] print("Image 1 has a face!") for (x, y, w, h) in faces2:
# ----------- FUNÇÃO PARA LER O ARQUIVO E ADICIONAR OS NOMES E IDs NOS TUPLES import webbrowser import cv2 # Biblioteca de captura de vídeo import math # Biblioteca de rotação de imagens import time # Biblioteca de contagem de tempo import os # Biblioteca de Arquivos now_time = time.time() face = cv2.CascadeClassifier('Haar/haarcascade_frontalcatface.xml') # Classificador "face frontal" Haar Cascade glass_cas = cv2.CascadeClassifier('Haar/haarcascade_eye_tree_eyeglasses.xml') # Classificador "olho" Haar Cascade WHITE = [255, 255, 255] def FileRead(): Info = open("Names.txt", "r")# Abrir o arquivo de texto em modo read NAME = [] # A tupla para armazenar nomes while (True): # Leia todas as linhas no arquivo e armazene-as em duas tuplas Line = Info.readline() if Line == '': break NAME.append(Line.split(",")[1].rstrip()) print(NAME) return NAME # Retorne as duas tuplas def GetSite(): Info = open("Names.txt", "r")# Abrir o arquivo de texto em modo read SITE = [] # A tupla para armazenar nomes while (True): # Leia todas as linhas no arquivo e armazene-as em duas tuplas Line = Info.readline()
import cv2 #importing OpenCV Python Interface webcam = cv2.VideoCapture(0) #created VideoCapture object and passed the device index(0), since there is only one webcam connected to my computer faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") # Create the haar cascade while True: ret, frame = webcam.read() #capturing frame by frame gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #applying operations, converting from BGR to GRAY faces = faceCascade.detectMultiScale( #detect faces in the image gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30) #flags = cv2.CV_HAAR_SCALE_IMAGE ) print("Found {0} faces!".format(len(faces))) #print the number of faces found for (x, y, w, h) in faces: #draw a rectangle around the faces cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.imshow('frame', frame) #display the resulting frame if cv2.waitKey(1) == 113: #waiting for the 'q' key to be pressed break
def run(glassesAddr): detector = dlib.get_frontal_face_detector() path = os.path.join(os.path.dirname(__file__), "datas", "shape_predictor_81_face_landmarks.dat") predictor = dlib.shape_predictor(path) # 打開臉部照片 path = os.path.join(os.path.dirname(__file__), "images", "saved.jpg") faceImg = cv2.imread(path) faceImg = imutils.resize(faceImg, width=640) faceImg_gray = cv2.cvtColor(faceImg, cv2.COLOR_RGB2GRAY) rects = detector(faceImg_gray, 1) distanceOfEye = [] leftEye = [] rightEye = [] faceWidth = [] bridge = [] # 標記特徵點 for i in range(len(rects)): landmarks = np.matrix([[p.x, p.y] for p in predictor(faceImg, rects[i]).parts()]) for idx, point in enumerate(landmarks): pos = (point[0, 0], point[0, 1]) if ((idx + 1) == 39 or (idx + 1) == 44): distanceOfEye.append(pos) if ((idx + 1) == 37 or (idx + 1) == 40): leftEye.append(pos) if ((idx + 1) == 43 or (idx + 1) == 46): rightEye.append(pos) if ((idx + 1) == 1 or (idx + 1) == 17): faceWidth.append(pos) if ((idx + 1) == 28): bridge.append(pos) # 利用cv2.circle給每個特徵點畫一個圈,共81個 cv2.circle(faceImg, pos, 7, color=(255, 255, 255)) # 利用cv2.putText輸出1-81 font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(faceImg, str(idx + 1), pos, font, 0.8, (0, 255, 0), 1, cv2.LINE_AA) path = os.path.join(os.path.dirname(__file__), "images", "saved.jpg") faceImg = cv2.imread(path) # 打開眼鏡照片 path = os.path.join(os.path.dirname(__file__), glassesAddr) glassesImg = cv2.imread(path) glassesImg = imutils.resize(glassesImg, width=int(Distance(distanceOfEye) * 2.5)) # 把臉部照片轉正 tempImg = rotate(faceImg, GetAngle(faceWidth)) # 開始合成臉部照片和眼鏡照片 並把照片轉回原本的樣子 src_mask = 255 * np.ones(glassesImg.shape, glassesImg.dtype) center = (bridge[0][0], bridge[0][1] + 8) outputImg = cv2.seamlessClone(glassesImg, tempImg, src_mask, center, cv2.MIXED_CLONE) outputImg = rotate(outputImg, -GetAngle(faceWidth)) # 開啟人臉辨識器 classfier = cv2.CascadeClassifier( 'D:\\opencv\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_alt2.xml' ) gray = cv2.cvtColor(faceImg, cv2.COLOR_BGR2GRAY) faces = classfier.detectMultiScale(gray, scaleFactor=1.08, minNeighbors=5, minSize=(32, 32)) # 抓出人臉的位置 for (x, y, w, h) in faces: a = x + w / 2 b = y + h / 2 center = (int(a), int(b)) # 只剪取人臉 然後把臉貼回原照片 -> 目的是為了去掉旋轉後留下的黑色區塊 tempImg = outputImg[int(b - ((h / 2) * 1.2)):int(b + ((h / 2) * 1.2)), int(a - ((w / 2) * 1.2)):int(a + ((w / 2) * 1.2))] faceImg[int(b - ((h / 2) * 1.2)):int(b + ((h / 2) * 1.2)), int(a - ((w / 2) * 1.2)):int(a + ((w / 2) * 1.2))] = tempImg path = os.path.join(os.path.dirname(__file__), "images", "result.jpg") cv2.imwrite(path, faceImg)
# OpenCV program to detect face in real time # import libraries of python OpenCV # where its functionality resides import cv2 # load the required trained XML classifiers # https://github.com/Itseez/opencv/blob/master/ # data/haarcascades/haarcascade_frontalface_default.xml # Trained XML classifiers describes some features of some # object we want to detect a cascade function is trained # from a lot of positive(faces) and negative(non-faces) # images. face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # https://github.com/Itseez/opencv/blob/master # /data/haarcascades/haarcascade_eye.xml # Trained XML file for detecting eyes eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') # capture frames from a camera cap = cv2.VideoCapture(0) # loop runs if capturing has been initialized. while 1: # reads frames from a camera ret, img = cap.read() # convert to gray scale of each frames gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
import cv2 import pickle faces_cascade = cv2.CascadeClassifier( 'cascades/data/haarcascade_frontalface_alt2.xml') # cascade for the eyes and the smile eye_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_eye.xml') smile_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_smile.xml') flag = False flag2 = True recognizer = cv2.face.LBPHFaceRecognizer_create( ) # adding face recognizer from faces_train recognizer.read("trainner.yml") # bring in the trained data file # to label the recognized image we are loading the pickle file we created labels = {"person_name": 1} with open("labels.pickle", 'rb') as f: og_labels = pickle.load(f) labels = {v: k for k, v in og_labels.items()} cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() frame = cv2.flip(frame, 1) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faces_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=3) for (x, y, w, h) in faces: # print(x,y,w,h) # commented upper line to just see the clear output if it recognize me or not
# 捕获指定摄像头的实时视频流 cap = cv2.VideoCapture(int(sys.argv[1])) # 人脸识别分类器本地存储路径 cascade_path = "C:/Programs/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_alt.xml" # 循环检测识别人脸 while True: _, frame = cap.read() # 读取一帧视频 # 图像灰化,降低计算复杂度 frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 使用人脸识别分类器,读入分类器 cascade = cv2.CascadeClassifier(cascade_path) # 利用分类器识别出哪个区域为人脸 faceRects = cascade.detectMultiScale(frame_gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32)) if len(faceRects) > 0: for faceRect in faceRects: x, y, w, h = faceRect # 截取脸部图像提交给模型识别这是谁 image = frame[y - 10: y + h + 10, x - 10: x + w + 10] faceID = model.face_predict(image) print(faceID) # 判断识别出的是谁 who = '' if faceID == 0:
cursor = conn.execute(cmd) isRecordExist = 0 # Neu gia tri ID da co thi update nguoc lai insert for row in cursor: isRecordExist = 1 if (isRecordExist == 1): cmd = "UPDATE facedata SET Name='" + str(Name) + "'WHERE ID=" + str(Id) else: cmd = "INSERT INTO facedata(ID,Name) Values(" + str(Id) + ",'" + str( Name) + "')" conn.execute(cmd) conn.commit() conn.close() faces_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml') cam = cv.VideoCapture(0) ident = input('Enter your ID: ') name = input('Enter your name: ') insertOrUpdate(ident, name) number_sample = 0 while True: ret, img = cam.read() img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # phat hien khuon mat faces = faces_cascade.detectMultiScale(img_gray, 1.3, 5) for (x, y, w, h) in faces: number_sample = number_sample + 1 # luu khuon mat dung dia chi file dataset cv.imwrite(
import cv2 import os cam = cv2.VideoCapture(0) cam.set(3, 640) # set video width cam.set(4, 480) # set video height face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # enter unique number id for face face_id = input('\n enter face id : ') print("\n Now camera is opening ...") count = 0 while(True): ret, img = cam.read() img=cv2.flip(img,+1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_detector.detectMultiScale(gray, 1.3, 1) for (x,y,w,h) in faces: cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2) count += 1 # directory for DataSet where will be store all face sample cv2.imwrite("DataSet/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w]) cv2.imshow('dataSetCreater', img)
import cv2 import os import imutils personName = 'Vlady' dataPath = 'C:/Users/Nils Choque/Desktop/Reconocimiento Facial/Capturas' personPath = dataPath + '/' + personName if not os.path.exists(personPath): print('Carpeta creada: ', personPath) os.makedirs(personPath) cap = cv2.VideoCapture('Vlady.mp4') faceClassif = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') count = 0 while True: ret, frame = cap.read() if ret == False: break frame = imutils.resize(frame, width=640) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) auxFrame = frame.copy() faces = faceClassif.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) rostro = auxFrame[y:y + h, x:x + w] rostro = cv2.resize(rostro, (150, 150), interpolation=cv2.INTER_CUBIC) cv2.imwrite(personPath + '/rostro_{}.jpg'.format(count), rostro) count = count + 1 cv2.imshow('frame', frame) k = cv2.waitKey(1) if k == 27 or count >= 300: