Face comparison of two images using Tensorflow Lite and Google ML Kit library

246 Views Asked by At

I am trying to compare 2 images , I cropped face from images now I want to compare them

But below codes have errors , unable to fix it, Please help,

Below is my code which I am trying to compare faces which return true and false if match success or fail

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
        
    }
0

There are 0 best solutions below