- 需求来源
在一次开发脚本的时候,突发奇想使用go语言来完成,其中一个功能就是找图返回坐标,话不多说,上代码。 - 具体实现
import (
"encoding/base64"
"os"
"image"
"image/color"
"image/draw"
)
type Position struct {
X int
Y int
}
func FindImgPos(dst string,src string) (Position,bool) {
var pos Position
a, err := os.Open(src)
if err != nil {
return pos,false
}
defer a.Close()
b, err := os.Open(dst)
if err != nil {
return pos,false
}
defer b.Close()
imgA, err := png.Decode(a)
if err != nil {
return pos,false
}
imgB, err := png.Decode(b)
if err != nil {
return pos,false
}
imgANRGBA := image.NewNRGBA(imgA.Bounds())
if imgANRGBA == nil {
imgANRGBA = image.NewNRGBA(imgA.Bounds())
}
color.NRGBA{}.RGBA()
draw.Draw(imgANRGBA, imgANRGBA.Bounds(), imgA, imgA.Bounds().Min, draw.Src)
imgBNRGBA := image.NewNRGBA(imgB.Bounds())
if imgBNRGBA == nil {
imgBNRGBA = image.NewNRGBA(imgB.Bounds())
}
color.NRGBA{}.RGBA()
draw.Draw(imgBNRGBA, imgBNRGBA.Bounds(), imgB, imgB.Bounds().Min, draw.Src)
boundsA := imgANRGBA.Bounds()
pixA := make([]byte, boundsA.Dx()*boundsA.Dy()*4)
copy(pixA, imgANRGBA.Pix)
boundsB := imgBNRGBA.Bounds()
pixB := make([]byte, boundsB.Dx()*boundsB.Dy()*4)
copy(pixB, imgBNRGBA.Pix)
found := false
for y := 0; y < boundsA.Dy()-boundsB.Dy(); y++ {
for x := 0; x < boundsA.Dx()-boundsB.Dx(); x++ {
match := true
for j := 0; j < boundsB.Dy() && match; j++ {
for i := 0; i < boundsB.Dx() && match; i++ {
if pixA[(y+j)*boundsA.Dx()*4+(x+i)*4] != pixB[j*boundsB.Dx()*4+i*4] ||
pixA[(y+j)*boundsA.Dx()*4+(x+i)*4+1] != pixB[j*boundsB.Dx()*4+i*4+1] ||
pixA[(y+j)*boundsA.Dx()*4+(x+i)*4+2] != pixB[j*boundsB.Dx()*4+i*4+2] ||
pixA[(y+j)*boundsA.Dx()*4+(x+i)*4+3] != pixB[j*boundsB.Dx()*4+i*4+3] {
match = false
}
}
}
if match {
pos.X=x
pos.Y=y
fmt.Printf("B 图片在 A 图片中的位置为 (%d, %d)\n", x, y)
found = true
}
}
}
if !found {
return pos,false
}
return pos,true
}