Skip to content

Instantly share code, notes, and snippets.

@robherley
Created February 4, 2020 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robherley/2382063d7e14e9f0d1eee9a8f5bdb209 to your computer and use it in GitHub Desktop.
Save robherley/2382063d7e14e9f0d1eee9a8f5bdb209 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"os"
"github.com/nfnt/resize"
"gocv.io/x/gocv"
)
const threshold float32 = .75
func main() {
full := gocv.IMRead("img/full.png", gocv.IMReadColor)
defer full.Close()
hashtag := gocv.IMRead("img/hashtag.png", gocv.IMReadColor)
defer hashtag.Close()
result := gocv.NewMat()
defer result.Close()
emptyMask := gocv.NewMat()
defer emptyMask.Close()
gocv.MatchTemplate(full, hashtag, &result, gocv.TmCcoeffNormed, emptyMask)
var matches []image.Rectangle
hashW := hashtag.Cols()
hashH := hashtag.Rows()
for col := 0; col < result.Cols(); col++ {
for row := 0; row < result.Rows(); row++ {
val := result.GetFloatAt(row, col)
if val >= threshold {
rect := image.Rect(col, row, col+hashW, row+hashH)
matches = append(matches, rect)
fmt.Println(rect, "=>", val)
}
}
}
for _, rect := range matches {
gocv.Rectangle(&full, rect, color.RGBA{0, 0, 0, 1}, 6)
}
gocv.IMWrite("output.png", full)
img, err := full.ToImage()
if err != nil {
panic(err)
}
bounds := img.Bounds()
resized := resize.Resize(uint(bounds.Dx()/2), uint(bounds.Dy()), img, resize.Lanczos3)
out, err := os.Create("output_resize.png")
if err != nil {
panic(err)
}
defer out.Close()
err = png.Encode(out, resized)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment