Go语言实现找图返回坐标

  1. 需求来源
    在一次开发脚本的时候,突发奇想使用go语言来完成,其中一个功能就是找图返回坐标,话不多说,上代码。
  2. 具体实现
/*
Authorization:Aluncca
p:16685034116
*/
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 图片
	a, err := os.Open(src)
	if err != nil {
		return pos,false
	}
	defer a.Close()

	// 打开 B 图片
	b, err := os.Open(dst)
	if err != nil {
		return pos,false
	}
	defer b.Close()

	// 解码 A 图片
	imgA, err := png.Decode(a)
	if err != nil {
		return pos,false
	}

	// 解码 B 图片
	imgB, err := png.Decode(b)
	if err != nil {
		return pos,false
	}

	// 将 A 图片的类型转换为 *image.NRGBA
	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)


	// 将 B 图片的类型转换为 *image.NRGBA
	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)

	// 获取 A 图片的像素数据
	boundsA := imgANRGBA.Bounds()
	pixA := make([]byte, boundsA.Dx()*boundsA.Dy()*4)
	copy(pixA, imgANRGBA.Pix)

	// 获取 B 图片的像素数据
	boundsB := imgBNRGBA.Bounds()
	pixB := make([]byte, boundsB.Dx()*boundsB.Dy()*4)
	copy(pixB, imgBNRGBA.Pix)

	// 查找 B 图片在 A 图片中的位置
	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
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值