Thứ Tư, 26 tháng 8, 2020

Xây dựng api tìm kiếm khuôn mặt trong database sử dụng cube trong postgresql

 Bước 1: Install postgresql từ Dockerfile

FROM postgres:10.6
MAINTAINER nikhil baby <nikhil_baby@hotmail.com>

RUN apt-get update && apt-get install -y build-essential curl postgresql-server-dev-10
RUN curl https://ftp.postgresql.org/pub/source/v10.6/postgresql-10.6.tar.bz2 -o /postgresql-10.6.tar.bz2
RUN cd / && tar xvf postgresql-10.6.tar.bz2
RUN cd /postgresql-10.6/contrib/cube && sed -i 's/#define CUBE_MAX_DIM (100)/#define CUBE_MAX_DIM (128)/' cubedata.h && \
    USE_PGXS=true make && USE_PGXS=true make install

Bước 2: Tạo extension cube và tạo bảng

CREATE EXTENSION CUBE

CREATE TABLE images (name text, vector cube);

 Bước 3: Chuyển khuôn mặt thành định dạng vector 128d sử dụng face_recognition và lưu vào db

image = face_recognition.load_image_file(pathImg)

conn = psycopg2.connect(host="localhost",database="postgres", user="postgres", password="mysecretpassword")

face_encoding = face_recognition.face_encodings(image)[0]        

face_encoding_string = ""

name='abc'    

for distance in face_encoding:
    face_encoding_string+=str(distance)
    face_encoding_string+=str(",")
        

face_encoding_string = face_encoding_string[:-1]

print(face_encoding_string)
        

cur = conn.cursor()

cur.execute("INSERT INTO images (name, vector) VALUES (name, '"+face_encoding_string+"')");

 

 Bước 4: Tìm kiếm ảnh trong db

conn = psycopg2.connect(host="localhost",database="postgres", user="postgres", password="mysecretpassword")

image = face_recognition.load_image_file(pathFileSearch)
face_encoding = face_recognition.face_encodings(image)[0]

 

face_encoding_string = ""

for distance in face_encoding:
        face_encoding_string+=str(distance)
        face_encoding_string+=str(",")

face_encoding_string = face_encoding_string[:-1]      
tempstring = "SELECT name FROM images ORDER BY vector<-> cube(array["+face_encoding_string+"]) LIMIT 1"

cur = conn.cursor()
cur.execute(tempstring)
print(cur.fetchall())
conn.commit()
conn.close()