使用 Tensorflow Lite 和 Google ML Kit 库对两个图像进行人脸比较

问题描述 投票:0回答:1

我正在尝试比较 2 张图像,我从图像中裁剪了脸部,现在我想比较它们

但是下面的代码有错误,无法修复,请帮忙,

下面是我的代码,我试图比较面部,如果匹配成功或失败,则返回 true 和 false

func compareFaceImages(image1: UIImage, image2: UIImage) -> Bool {
        // Load the TensorFlow Lite model
        guard let modelPath = Bundle.main.path(forResource: "mobile_face_net", ofType: "tflite"),
              let model = try? Interpreter(modelPath: modelPath) else {
            print("Failed to load the TensorFlow Lite model.")
            return false
        }

        // Preprocess the input images
        guard let inputImage1 = preprocessImage(image: image1, size: CGSize(width: 112, height: 112)),
              let inputImage2 = preprocessImage(image: image2, size: CGSize(width: 112, height: 112)) else {
            print("Failed to preprocess input images.")
            return false
        }

        // Allocate tensors for input and output
        guard let inputTensor1 = try? model.input(at: 0),
              let inputTensor2 = try? model.input(at: 1),
              let outputTensor1 = try? model.output(at: 0),
              let outputTensor2 = try? model.output(at: 1) else {
            print("Failed to get input and output tensors from the TensorFlow Lite model.")
            return false
        }
        let inputData1 = inputData(from: inputImage1)
        let inputData2 = inputData(from: inputImage2)

        // Copy input data to input tensors
        guard let inputTensor1Data = try? Data(copyingBufferOf: inputData1),
              let inputTensor2Data = try? Data(copyingBufferOf: inputData2) else {
            print("Failed to create input tensor data.")
            return false
        }
        inputTensor1.data.copy(from: inputTensor1Data)
        inputTensor2.data.copy(from: inputTensor2Data)

        // Run the model
        do {
            try model.invoke()
        } catch {
            print("Failed to run the TensorFlow Lite model.")
            return false
        }

        // Get output data
        guard let embeddings1 = outputTensor1.data.toArray(type: Float32.self),
              let embeddings2 = outputTensor2.data.toArray(type: Float32.self) else {
            print("Failed to retrieve embeddings data from the TensorFlow Lite model.")
            return false
        }

        // Calculate the Euclidean distance between the embeddings
        let distance = calculateEuclideanDistance(embeddings1, embeddings2)
        let threshold: Float = 0.6 // Adjust the threshold as needed
        return distance <= threshold
        
    }
ios xcode swift4 tensorflow-lite swift4.2
1个回答
0
投票

您面临什么错误?能解决吗

© www.soinside.com 2019 - 2024. All rights reserved.