doutu3352 2016-07-19 19:19
浏览 303

在Golang中比较base64图像字符串

I have a service that compares two base64 encoded image strings

My initial attempt revealed that there is differences in metadata while the actual image (JPG) in this case is identical (size,resolution,dimensions,etc).

Is there a way to strip away much of the dynamic metadata so that I can just compare the visual aspect of the image?

Currently, I am using the following...

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
}
  • 写回答

1条回答 默认 最新

  • dongyaobo9081 2016-07-19 21:41
    关注

    Perceptual Hash is a library to calculate a phash; a hash of an image based on visual characteristics. github.com/carlogit/phash is a golang implementation. It has functions to create and compare two hashes to give a 'distance' indicating how dissimilar two images are.

    Out of interest I gave it a try, it's simple to use and effective with some test images. For example:

    Queenstown Queenstown distance: 0

    Queenstown Queenstown Gold distance: 2

    Queenstown Homer Saddle 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>
    ", os.Args[0])
        }
    
        a := hash(os.Args[1])
        b := hash(os.Args[2])
        distance := phash.GetDistance(a, b)
    
        fmt.Printf("distance: %d
    ", 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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大