【问题标题】:Comparing base64 image strings in Golang比较 Golang 中的 base64 图像字符串
【发布时间】:2018-08-28 02:04:49
【问题描述】:

我有一个比较两个 base64 编码图像字符串的服务

我最初的尝试表明元数据存在差异,而在这种情况下实际图像 (JPG) 是相同的(大小、分辨率、尺寸等)。

有没有办法去除大部分动态元数据,以便我可以比较图像的视觉方面?

目前,我正在使用以下...

package converter

import (
    "bufio"
    "encoding/base64"
    "log"
    "os"
)

func Base64(path string) (string, error) {
    imgFile, err := os.Open(path)
    if err != nil {
        log.Fatalln(err)
    }

    defer imgFile.Close()

    // create a new buffer base on file size
    fInfo, _ := imgFile.Stat()
    var size int64 = fInfo.Size()
    buf := make([]byte, size)

    // read file content into buffer
    fReader := bufio.NewReader(imgFile)
    fReader.Read(buf)

    // convert the buffer bytes to base64 string - use buf.Bytes() for new image
    imgBase64Str := base64.StdEncoding.EncodeToString(buf)

    return imgBase64Str,nil
}

【问题讨论】:

  • jpeg 是一种有损压缩,并且因编码器/解码器而异,因此您无法准确比较来自不同 jpeg 文件的图像数据(并且比较视觉相似性是 SO 答案的一个非常大的主题)。但是,如果文件大小完全相同,那么您可能拥有相同的图像并且错误地比较了 base64。 (而且比较哈希效率更高,为什么要比较整个图像数据?)
  • 两种可能:1) 实际图像数据相同,只是标题不同,2) 图像看起来相同,但实际上在层级不同图像数据。对于前者,您应该能够剥离元数据并仅比较图像数据。这将需要一些JPEG格式的知识。对于后者,您需要某种“图像哈希”算法,例如光DNA。这些算法在视觉上散列图像,旨在对缩放和旋转具有鲁棒性。

标签: image go base64


【解决方案1】:

Perceptual Hash 是一个计算 phash 的库;基于视觉特征的图像哈希。 github.com/carlogit/phash 是一个 golang 实现。它具有创建和比较两个哈希值的功能,以给出一个“距离”,表明两个图像的不同程度。

出于兴趣,我试了一下,它使用简单,对一些测试图像有效。例如:

distance: 0

distance: 2

distance: 32

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/carlogit/phash"
)

func main() {
    if len(os.Args) < 3 {
        log.Fatalf("usage: %s <ImageFileA> <ImageFileB>\n", os.Args[0])
    }

    a := hash(os.Args[1])
    b := hash(os.Args[2])
    distance := phash.GetDistance(a, b)

    fmt.Printf("distance: %d\n", distance)
}

//hash returns a phash of the image
func hash(filename string) string {
    img, err := os.Open(filename)
    if err != nil {
        log.Fatal(err)
    }
    defer img.Close()

    ahash, err := phash.GetHash(img)
    if err != nil {
        log.Fatal(err)
    }
    return ahash
}

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 2016-03-26
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多