程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[python] to FaceRecognizeSys [Doing...]

編輯:Python

List of articles

  • Face recognition system
    • Project technology stack
    • Face Rec
      • flash
      • SQLAlchemy
      • Falsk WTF
      • bootstrap Quick Render
      • Template
      • Commonly used Web frame
      • Decorator
        • Router( route )
        • flask_login
        • abnormal
        • Manager
      • dlib (python library )
        • hog Extract feature function
        • cnn Extract feature function
      • python Basics
        • Duck type and polymorphism
        • Abstract base class
        • python function
    • Get ready :
    • function :

Time event remarks 2022.06.21startJucwJucw

People who can achieve great things will always make warm moves , Like give it to me Point a praise

Face recognition system

Project technology stack

Face Rec

Technology stack

python

mysql

flash

flask.pocoo.org

Chinese document :https://dormousehole.readthedocs.io/en/latest/quickstart.html

course :

https://flask.net.cn/tutorial/index.html

lightweight framework
Flask It's often called a microframe , Because the core functions include Werkzeug Of WSGI And routing and based on Jinja2 Template engine for . Besides ,Flask The framework also supports cookie And sessions and Web assistant , Such as JSON, Static files, etc . obviously , This is important for developing complete Web Not enough for applications . That's why we have to Flask Extension plug-in . Flask Expand to Flask The framework provides extensibility
// Read more :https://www.yiibai.com/flask/flask_extensions.html#article-start

SQLAlchemy

https://zhuanlan.zhihu.com/p/27400862
OMR Object relation mapping https://www.cnblogs.com/huanhang/p/6054908.html
SQLAlchemy It's a powerful Python ORM tool kit , Good reputation

Database connection

Database operation logic

Edit user
according to id Find the corresponding user , Update user data

user = User.query.get_404(id) # If id by none, return 404, Otherwise, return to call 

Delete user

Adding roles :

db.session.add(role)

db.session.commit() Commit to database

Add users :

When calling the add user function , Generate a default administrator account ,

engine = create_engine('dialect+driver://username:[email protected]:port/database')
dialect: Database type
driver: Database driven selection
username: Database user name
password: User password
host: Server address
port: port
database: database

operation

session( conversation ) The concept of , It can be regarded as an object for managing persistent database connections , Below are completely transparent connection pools and transactions

get_session Under configure Can be controlled auto_commit Parameters ,= False Time write operations are not placed in transactions by default ,SQLAlchemy The default is True

session.add The function will put Model Join the current persistent space ( It can be downloaded from session.dirty notice ), until commit When the update

Falsk WTF

wtf form Protect forms from cross site scripting attacks

Inherit Form Class or subclass

Validator validator There are message Parameters ;

Required Rep is required

Form validation

Required() , validators

Judge whether the user exists

User.query.filter_by(number=field.data).first()

Inherited parent class

super(EditForm, self).__init__(*args, **kargs) Single parameter and multi parameter

bootstrap Quick Render

Use bootstrap A predefined form style renders the entire Flask-WTF Forms ,

wtf.quick_form() The argument to the function is Flask-WTF Form object

Bootstrap

Bootstrap Is for rapid development Web Front end framework for applications and websites .Bootstrap Is based on HTML、CSS、JAVASCRIPT Of

Definition of columns

https://blog.csdn.net/liyang_nash/article/details/81163782

{% import "bootstrap/wtf.html" as wtf %}
<form class="form" method="POST">
{
{ form.hidden_tag() }}
{
{ wtf.form_field(form.title) }} % Use bootstrap Use form.title form.body form.submit Render using default
{
{ wtf.form_field(form.body) }}
{
{ wtf.form_field(form.submit) }}
</form>

Use the default style of the form to render

{% import "bootstrap/wtf.html" as wtf %}
{
{ wtf.quick_form(form) }}

Template

Base.html

Base class

{% extends "bootstrap/base.html" %} Inherit boostrap In the base class

form.hidden_tag()

The template parameter will be replaced with a hidden field , It is used to realize the activation in the configuration CSRF Protect . If you have activated CSRF, This field needs to appear in all your forms .

Form login

StringField , PasswordField , BooleanField, SubmitField, IntegerField, FileField,

https://www.yiibai.com/flask/flask_wtf.html

Commonly used Web frame

Django

Decorator

Router( route )

@app.route('/',methods=['Get','POST'])

flask_login

@login_required

Decorator , Judge whether the user is logged in , Only the logged in user can access the request

and django Is the same property

abnormal

The catch function throws an exception , Same as Vue Grammatical similarity

@app.errorhandler(404) # 

Manager

Instructions can be used at the terminal to operate the program

command The function of the decorator , Custom command

Use scenarios : Create some sensitive data ( Backstage Administrator ), Batch add test data

dlib (python library )

Machine learning open source library ,, Contains many algorithms C++ Cross platform common library written by technology

dlib.get_frontal_face_detector Function to realize the visualization of face detection

hog Extract feature function

1.1. be based on HOG Face detection based on feature and linear classifier Here is the classic HOG(Histogram of Oriented Gradients) features Combined with linear classifier 、 Image pyramid (image pyramid) And sliding window detection mechanism (sliding window detection scheme) Implemented face detector .

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import dlib
detector = dlib.get_frontal_face_detector()
def face_detect(imgfile):
win = dlib.image_window()
print("Processing file: {}".format(imgfile))
img = dlib.load_rgb_image(imgfile)
# Face detection 
dets = detector(img, 1)
# len(dets) That is, the number of detected faces 
print("Number of faces detected: {}".format(len(dets)))
# Traverse the coordinates of all detected faces 
# left: The distance from the left side of the face to the left edge of the picture 
# right: The distance from the right side of the face to the left edge of the picture 
# top: Distance between the upper edge of the face and the upper edge of the picture 
# bottom: The distance between the lower edge of the face and the upper edge of the picture 
for i, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
i, d.left(), d.top(), d.right(), d.bottom()))
win.clear_overlay()
win.set_image(img)
win.add_overlay(dets)
dlib.hit_enter_to_continue()
def face_detect_with_scores(imgfile):
win = dlib.image_window()
# If you want to get more comprehensive detection information , Such as the score of each test result (score).
# score The bigger the value is. , The higher the reliability of the test .
img = dlib.load_rgb_image(imgfile)
# The third parameter -1 Used to set and adjust the detection threshold ;
# If the parameter value is negative , Returns more results ;
# If the parameter value is a positive number , Returns fewer results .
dets, scores, idx = detector.run(img, 1, -1)
for i, d in enumerate(dets):
print("Detection {}, score: {}, face_type:{}".format(
d, scores[i], idx[i]))
win.clear_overlay()
win.set_image(img)
win.add_overlay(dets)
dlib.hit_enter_to_continue()
if __name__ == '__main__':
imgfile = "test.jpg"
face_detect(imgfile)
face_detect_with_scores(imgfile)

cnn Extract feature function

Use pre trained CNN Model for face detection in images .

be based on CNN The model ratio is based on HOG The face detection accuracy of feature model is higher . But more computing resources are needed , That is to say GPU Only by running on the can we have a better running speed .

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import dlib
# Load pre training face detection CNN Model 
cnn_face_model = "mmod_human_face_detector.dat"
cnn_face_detector = dlib.cnn_face_detection_model_v1(cnn_face_model)
def cnn_face_detect(imgfile):
win = dlib.image_window()
print("Processing file: {}".format(imgfile))
img = dlib.load_rgb_image(imgfile)
# CNN Face detector 
# The detector returns mmod_rectangles object, It contains mmod_rectangle objects list .
# mmod_rectangle object There are two variables :
# [1]. dlib.rectangle object
# [2]. confidence score
dets = cnn_face_detector(img, 1)
# Batch test pictures 
# dets = cnn_face_detector([image list], upsample_num, batch_size = 128)
# len(dets) That is, the number of detected faces 
print("Number of faces detected: {}".format(len(dets)))
for i, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {} Confidence: {}".format(
i, d.rect.left(), d.rect.top(), d.rect.right(), d.rect.bottom(), d.confidence))
rects = dlib.rectangles()
rects.extend([d.rect for d in dets])
win.clear_overlay()
win.set_image(img)
win.add_overlay(rects)
dlib.hit_enter_to_continue()
if __name__ == '__main__':
imgfile = "test.jpg"
cnn_face_detect(imgfile)

https://cloud.tencent.com/developer/article/1401153

video : hibernate

python Basics

python Basics

Duck type and polymorphism

Built in type ,getitems Just specify the method name , Many objects can write many magic functions , Iteratable properties

itenext Iterative type

call Callable type

Abstract base class

Dynamic language , In itself, it supports polymorphic languages , There is no need to specify the type , The error will only be known at runtime

No need to inherit the specified class , Duck type is a concept of dynamic language design ;

hasattr(com,"_len__") # Determine whether the attribute is included ( Method )
In some cases, it is necessary to determine an object type , Need abstract base class
Force a subclass to implement certain methods
Define an abstract base class , Users use it later according to their own needs , The way to realize yourself ,
Subclasses implement their own methods of the base class
abs
collections.abc
Two different base classes
Use decorators @abc.abstractmethod
During initialization, if there is no subclass or implementation , An exception will be thrown at this time , Subclasses are required to implement abstract base classes ;
template function __class__
isinstance() Judging by examples Internal function , Mandatory provisions for interfaces

isinstance and type

isinstance Check whether the type is consistent , return True perhaps False, Will find according to the inheritance relationship

is and == Symbol difference

type(b) is B # The comparison is id Are they the same? ,

== The symbol is to judge whether the values are the same

Class variables and object variables ( Instance variables )

Variables in a class are called class variables

Initialize parameters ,self. Variables are object variables : First, find the instance variable , Could not find the class variable that will be looked up

For class variables, you won't look for instance variables ;

class A:
aa = 0
def __init__(self,x,y):
self.x = x
self.y = y
a = A()
A.aa = 11
a.aa = 100 # Here, whether class variables are overwritten by using instances to modify class variables 
print(a.aa) # 100 First, we will find in the instance aa Value 
print(A.aa) # 11

python function

__repr__()

Built in functions by overriding , To print the characters to be displayed

Get ready :

Use conda The virtual environment runs the project

  1. Install dependent packages :
    pip install -r requirements.txt

function :

  1. Update the database :python app.py db upgrade

  2. Generate administrator user :python app.py init

  3. function :python app.py runserver


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved