1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
histogram.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-06-01 16:22 . init
package images
import (
"bufio"
"image"
"io"
"math"
"os"
)
// Histogram 相似图片识别(直方图)
type Histogram struct {
redBins int
greenBins int
blueBins int
histogram []float64
}
func NewHistogram() *Histogram {
binCount := 4
h := &Histogram{
redBins: binCount,
greenBins: binCount,
blueBins: binCount,
histogram: make([]float64, binCount*binCount*binCount),
}
return h
}
func (hm *Histogram) OpenFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
return hm.Open(bufio.NewReader(file))
}
func (hm *Histogram) Open(reader io.Reader) error {
img, _, err := image.Decode(reader)
if err != nil {
return err
}
return hm.OpenImage(img)
}
func (hm *Histogram) OpenImage(img image.Image) error {
width := img.Bounds().Dx()
height := img.Bounds().Dy()
img.ColorModel()
total := 0
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
r, g, b, _ := img.At(x, y).RGBA()
red := index(hm.redBins, r>>8, 255)
green := index(hm.greenBins, g>>8, 255)
blue := index(hm.blueBins, b>>8, 255)
idx := red + green*hm.redBins + blue*hm.redBins*hm.greenBins
hm.histogram[idx]++
total += 1
}
}
// start to normalize the histogram data
for i := 0; i < len(hm.histogram); i++ {
hm.histogram[i] = hm.histogram[i] / float64(total)
}
return nil
}
func (hm *Histogram) Data() []float64 {
return hm.histogram
}
// Match 返回值大于等于0.8可以简单判断这两张图片内容一致
func (hm *Histogram) Match(dest *Histogram) float64 {
source := hm.Data()
candidate := dest.Data()
mixed := make([]float64, len(source))
for i := 0; i < len(source); i++ {
mixed[i] = math.Sqrt(source[i] * candidate[i])
}
similarity := 0.0
for i := 0; i < len(mixed); i++ {
similarity += mixed[i]
}
// The degree of similarity
return similarity
}
func index(binCount int, color uint32, maxColor uint32) int {
binIndex := int(float32(color) / float32(maxColor) * float32(binCount))
if binIndex >= binCount {
binIndex = binCount - 1
}
return binIndex
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.121

搜索帮助