from flask import Flask,request,render_template,redirect,url_for import cv2,face_recognition,re,json,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) 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'\xff\xd8\xff\xe0': return False elif data[6:] != b'JFIF\x00': 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("qqq.jpg", "wb") as w: w.write(file_data) if is_jpg("qqq.jpg")==True: image = face_recognition.load_image_file("qqq.jpg") face_locations = face_recognition.face_locations(image) print(face_locations) img = cv2.imread("qqq.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:\Users\Administrator\Desktop\image\%s.jpg"%uuid_str cv2.imwrite(path, img) face = Face(uuid_str,path) db.session.add(face) db.session.commit() data = { "index":"success", "img_name":uuid_str } return data else: data = { "index":"error" } 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)