1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| package main
import ( "fmt" "github.com/go-vgo/robotgo" "github.com/kbinani/screenshot" "gocv.io/x/gocv" "image" "image/color" "image/png" "os" )
func captureScreen() (*image.RGBA, error) { bounds := image.Rect(800, 600, 0, 0)
img, err := screenshot.CaptureRect(bounds) if err != nil { return nil, fmt.Errorf("无法截取屏幕图像: %v", err) }
return toRGBA(img), nil }
func toRGBA(img image.Image) *image.RGBA { bounds := img.Bounds() rgba := image.NewRGBA(bounds)
for x := bounds.Min.X; x < bounds.Max.X; x++ { for y := bounds.Min.Y; y < bounds.Max.Y; y++ { c := img.At(x, y) r, g, b, a := c.RGBA() rgba.SetRGBA(x, y, color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)}) } }
return rgba }
func saveImage(img image.Image, filename string) error { file, err := os.Create(filename) if err != nil { return err } defer file.Close()
err = png.Encode(file, img) if err != nil { return err }
return nil }
func findImageInScreen(targetImagePath string) (image.Point, error) { screenImg, err := captureScreen() if err != nil { return image.Point{}, fmt.Errorf("无法截取屏幕图像: %v", err) }
tmpFilename := "images\\search.png" err = saveImage(screenImg, tmpFilename) if err != nil { return image.Point{}, fmt.Errorf("无法保存截图:%v", err) } defer os.Remove(tmpFilename)
targetImage := gocv.IMRead(targetImagePath, gocv.IMReadColor) if targetImage.Empty() { return image.Point{}, fmt.Errorf("无法读取目标图片") } defer targetImage.Close()
searchImage := gocv.IMRead(tmpFilename, gocv.IMReadColor) if searchImage.Empty() { return image.Point{}, fmt.Errorf("无法读取搜索图片") } defer searchImage.Close()
result := gocv.NewMat() defer result.Close()
gocv.MatchTemplate(searchImage, targetImage, &result, gocv.TmCcoeffNormed, gocv.NewMat())
_, _, _, maxLoc := gocv.MinMaxLoc(result)
return maxLoc, nil }
func main() { targetImagePath := "images\\target.png"
loc, err := findImageInScreen(targetImagePath) if err != nil { fmt.Println("无法在屏幕上寻找目标图片:", err) return }
fmt.Printf("目标图片在屏幕上的坐标:(X:%d, Y:%d)\n", loc.X, loc.Y)
robotgo.MoveMouse(loc.X, loc.Y) robotgo.MouseClick("left", true)
fmt.Println("鼠标已经双击") }
|