python - 我如何获得opencv中显示的图像坐标

标签 python opencv image-processing pygame artificial-intelligence

抱歉,标题没有意义

我正在尝试制作一个点击球使其反弹的 ai。 对于上下文,这是应用程序的图片 enter image description here

在游戏中,当您点击小球时,它会上升,然后又会下降,而游戏的目的就是让它保持向上。

我已经写了一些代码,用 opencv 把图像变成一个蒙版,这是结果的图片

enter image description here

我现在需要做的是以像素/坐标为单位找到球的位置,这样我就可以让鼠标移动到它并单击它。顺便说一句,球在它的左右两侧都有一个边缘,所以它不仅会上下移动,还会左右移动。球也不是动画的,只是一个移动的图像。

我如何获得以像素/坐标为单位的球位置,以便我可以将鼠标移动到它。

这是我的代码的副本:

import numpy as np
from PIL import ImageGrab
import cv2
import time
import pyautogui


def draw_lines(img,lines):
    for line in lines:
        coords = line[0]
        cv2.line(img, (coords[0], coords[1]), (coords[2], coords[3]), [255,255,255], 3)

def process_img(original_image):
    processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
    processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300)
    vertices = np.array([[0,0],[0,800],[850,800],[850,0]
                         ], np.int32)
    processed_img = roi(processed_img, [vertices])

    # more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
    #                          edges       rho   theta   thresh         # min length, max gap:        
    lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180,      20,         15)
    draw_lines(processed_img,lines)
    return processed_img

def roi(img, vertices):
    #blank mask:
    mask = np.zeros_like(img)
    # fill the mask
    cv2.fillPoly(mask, vertices, 255)
    # now only show the area that is the mask
    masked = cv2.bitwise_and(img, mask)
    return masked
def main():
    last_time = time.time()
    while(True):
        screen =  np.array(ImageGrab.grab(bbox=(0,40, 800, 850)))
        new_screen = process_img(screen)
        print('Loop took {} seconds'.format(time.time()-last_time))
        last_time = time.time()
        cv2.imshow('window', new_screen)
        #cv2.imshow('window2', cv2.cvtColor(screen, cv2.COLOR_BGR2RGB))
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

def mouse_movement():
    ##Set to move relative to where ball is
    pyautogui.moveTo(300,400)
    pyautogui.click();
main()

抱歉,如果这令人困惑,但 brain.exe 已停止工作 :( 谢谢

最佳答案

你可以这样做:

1. 从屏幕截图中裁剪球的图像,等等。喜欢

img = cv2.imread("screenshot.jpg")
crop_img = img[y:y+h, x:x+w] # you will have to look for the parameters by trial and error

2。 使用 template matching查看图像中球的位置

3。 获取结果矩形中间的点并将鼠标移到那里

我希望这对您有所帮助,如果您需要更多关于如何实现这些的帮助,请随时询问

关于python - 我如何获得opencv中显示的图像坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54082938/

相关文章:

c - 在 OpenCV 中显示来自网络摄像头的视频

java - 在图像中查找特定颜色

c# - 使用 System.Drawing 从流中检测 CMYK

python - 嵌套列表对象不支持索引

Python StreamIO 从同一个流读取和写入

android - 这些opencv函数是由ARM NEON加速的吗?

python - 根据颜色执行物体识别

image-processing - 我在哪里可以找到解释 FFT 相位相关评分的良好信息来源

python - 如何在 Python 的多列中将输出写入 CSV

python - 如何使用 BeautifulSoup 获取 <tr> 中的特定 <td>