package com.base.filerecoveryrecyclebin.utils

import org.opencv.core.Core
import org.opencv.core.Mat
import org.opencv.core.MatOfFloat
import org.opencv.core.MatOfInt
import org.opencv.imgcodecs.Imgcodecs
import org.opencv.imgproc.Imgproc

object OpencvImageHelp {

    fun opencvCompareSimilar(path1: String, path2: String): Double {
        // 将File对象转换为Mat对象
        val image1 = Imgcodecs.imread(path1)
        val image2 = Imgcodecs.imread(path2)

        // 转换为灰度图
        val grayImage1 = Mat()
        val grayImage2 = Mat()
        Imgproc.cvtColor(image1, grayImage1, Imgproc.COLOR_BGR2GRAY)
        Imgproc.cvtColor(image2, grayImage2, Imgproc.COLOR_BGR2GRAY)

        // 计算直方图
        val histSize = MatOfInt(256)
        val range = MatOfFloat(0f, 256f)
        val hist1 = Mat()
        val hist2 = Mat()
        Imgproc.calcHist(mutableListOf(grayImage1), MatOfInt(0), Mat(), hist1, histSize, range)
        Imgproc.calcHist(mutableListOf(grayImage2), MatOfInt(0), Mat(), hist2, histSize, range)

        // 归一化直方图
        Core.normalize(hist1, hist1, 0.0, 1.0, Core.NORM_MINMAX, -1, Mat())
        Core.normalize(hist2, hist2, 0.0, 1.0, Core.NORM_MINMAX, -1, Mat())

        // 使用相关性方法比较直方图
        //HISTCMP_CORREL 相关性
        //HISTCMP_INTERSECT 交集
        val similarity: Double = Imgproc.compareHist(hist1, hist2, Imgproc.HISTCMP_CORREL)

        // 将相似度转换为百分比
        val similarityPercentage = similarity * 100.0

        return similarityPercentage
    }
}