创建一个带有面部兰标检测的 numpy 数组的文本文件



我正在尝试制作一个面部交换应用程序,我有面部特征点检测代码。但是,由于我是编程世界的新手,我使我的代码比需要的更长。我知道,有一些捷径可以做到这一点,我只是不知道怎么做。这是我的代码:

predictor_path = "C:\Users\G7K4\Desktop\FinalFaceSwap\shape_predictor_68_face_landmarks.dat"
filepath1 =  "C:\Users\G7K4\Desktop\FinalFaceSwap\Image\nil.jpg"
image1 = cv2.imread(filepath1)

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path) 
dets1 = detector(image1)
for k, d in enumerate(dets1):
shape = predictor(img1, d)
#Detect 68 facial landmark points
vec = np.empty([68, 2], dtype = int)
for b in range(68):
    vec[b][0] = shape.part(b).x
    vec[b][1] = shape.part(b).y
#write the detected file in text file
with open("Model1.txt","w") as file:
    for i in range(len(vec)):
        outer=""
        outer += str(vec[i])
        file.write(outer)
        file.write("n")
#read the text file and remove the brackets
with open("Model1.txt","r") as my_file:
    text=my_file.read()
    text= text.replace("[","")
    text= text.replace("]","")
#again write the file. 
with open("Model1.txt","w") as file:
    file.write(text)
#function for reading points from text file
def readPoints(path) :
    # Create an array of points.
    points = [];
    # Read points
    with open(path) as file :
        for line in file :
            x, y = line.split()
            points.append((int(x), int(y)))
    return points

所以,在这里,我需要检测面部特征并直接读取它,以便它可以用于面部交换。或者,如果无法完成,我需要检测面部特征并立即将其写入不带括号的文本文件中,这样,我就不必读写两次文本文件并删除括号。

有一个名为 imutils 的软件包用于处理 dlib 面部地标。运行pip install imutils进行安装。这是这样做的简短方法

from imutils import face_utils
shape = predictor(img1, d)
shape = face_utils.shape_to_np(shape)
# access the x-coordinate point 20 
x_20 = shape[20][0]
# access the y-coordinate point 54 
y_54 = shape[54][1]

您确实需要以文本格式编写 numpy 矩阵数据,并在以后删除括号。相反,numpy已经提供了用于序列化和反序列化目的的np.save()np.load()方法。

我将在这里为您提供一个示例,此外,将读取和写入函数封装在单独的方法中也是一种很好的做法,这样当您更改读/写逻辑时,您无需扫描整个代码。

创建随机面部特征点:

facial_points = np.zeros((68, 2), dtype=np.uint8)
# Fill in some absurd values:
for i in xrange(68):
    facial_points[i] = np.asarray([i, i%10])

读取和写入数据的实用方法:

def serialize_feature_points(feature_points, file_path):
    np.save(file_path, feature_points)

def deserialize_feature_points(file_path):
    return np.load(file_path)

是时候采取行动了:

serialize_feature_points(facial_points, "feature_points1.npy")
print deserialize_feature_points("feature_points1.npy")
[[ 0  0]
 [ 1  1]
 [ 2  2]
 .... 
 [65  5]
 [66  6]
 [67  7]]

最新更新