人脸识别

from flask import Flask,request
import cv2,face_recognition,re,uuid,pymysql
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.debug = True # 调试模式
pymysql.install_as_MySQLdb()
# 配置数据库
app.config["SQLALCHEMY_DATABASE_URI"]="mysql://root:123@127.0.0.1:3306/face"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
# 创建face表
class Face(db.Model):
    __tablename__ = "face"
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(32),doc="文件名",unique=True)
    path = db.Column(db.VARCHAR(255),doc="路径",unique=True)

    def __init__(self,name,path):
        self.name = name
        self.path = path

    def __repr__(self):
        return "face: %s %s %s " % (self.id,self.name,self.path)


# 判断是否为图片
def is_jpg(filename):
    data = open(filename,'rb').read(11)
    # print(data)
    # print(data[:4])
    # print(data[6:])
    if data[:4] != b'xffxd8xffxe0':
        return False
    elif data[6:] != b'JFIFx00':
        return False
    else:
        return True


# 配置路由,flask路由基于装饰器

@app.route('/',methods=['GET','POST'])
# 既要响应get和post请求
def index():
    if request.method == 'POST':
        res = request.get_data()

        # 去除多余的图片字段
        pattern1 = re.compile(b"-+w+s{2}(.*?s{2}){2}s{2}")
        pattern2 = re.compile(b"s{2}-+w+-+s{2}")
        res1 = re.match(pattern1, res)
        res2 = re.search(pattern2, res)
        file_data = res[res1.end():res2.start()]
        # 生成一个随机字符串
        uuid_str = uuid.uuid4().hex
        print(file_data)
        with open("res_jpg.jpg", "wb") as w:
            w.write(file_data)
        with open("res_png.png", "wb") as w:
            w.write(file_data)
        if is_jpg("res_jpg.jpg")==True:
            # 读取图片
            image = face_recognition.load_image_file("res_jpg.jpg")
            # 检测图片中的人脸,([1,1,1],[2,2,2])
            face_locations = face_recognition.face_locations(image)
            print(face_locations)
            img = cv2.imread("res_jpg.jpg")
            # 给人脸画框,左,上,宽,高
            for i in range(0, len(face_locations)):
                if i < len(face_locations):
                    cv2.rectangle(img, (face_locations[i][3], face_locations[i][0]),
                                  (face_locations[i][1], face_locations[i][2]),
                                  (0, 0, 255), 3)
                else:
                    break


            # cv2.namedWindow("sss")
            # cv2.imshow("sss", img)
            # cv2.waitKey(0)
            # 保存图片
            path = r"C:UsersAdministratorDesktopimage\%s.jpg"%uuid_str
            cv2.imwrite(path, img)
            # 写入数据库
            face = Face(uuid_str,path)
            db.session.add(face)
            db.session.commit()

            data = {
                "index":"success",
                "jpg_path":path
            }

            return data

        else:
            image = face_recognition.load_image_file("res_png.png")
            face_locations = face_recognition.face_locations(image)
            print(face_locations)
            img = cv2.imread("res_png.png")
            for i in range(0, len(face_locations)):
                if i < len(face_locations):
                    cv2.rectangle(img, (face_locations[i][3], face_locations[i][0]),
                                  (face_locations[i][1], face_locations[i][2]),
                                  (0, 0, 255), 3)
                else:
                    break

            # cv2.namedWindow("sss")
            # cv2.imshow("sss", img)
            # cv2.waitKey(0)
            path = r"C:UsersAdministratorDesktopimage\%s.png" % uuid_str
            cv2.imwrite(path, img)

            face = Face(uuid_str, path)
            db.session.add(face)
            db.session.commit()

            data = {
                "index": "success",
                "png_path": path
            }

            return data



    if request.method == 'GET':
        return "hello"

app.config['DEBUG'] = True





if __name__ == '__main__':
    # db.create_all()
    app.run(host="127.0.0.2",port=2333)
原文地址:https://www.cnblogs.com/xuezhihao/p/11394666.html