LoginSignup
0
0

pyautoguiで画像ファイルから特定の画像を探す方法

Last updated at Posted at 2024-05-06

結論

pyautoguiで画像ファイルから特定の画像を探すにはpyautogui.locate(対象画像ファイル, 探したい画像ファイル)を使うとOK
対象画像ファイル探したい画像ファイルが含まれているとあれこれ返ってくる

これだけだとあまりにもそっけないので、今後の自分のために発見までの道のりを記しておく

マニュアルを読んだ

マニュアルには現在表示されている画面から特定の画像を探すときに使うpyautogui.locateOnScreenについての説明がある

たとえば以下の画像quitBtn.pngが画面上にあるか探し出したいとする

quitBtn.png

そんな時は

pyautogui.locateOnScreen('quitBtn.png')

とすると場所情報などが返ってくる

似たような関数として画面上から画像を探し出し、その中心座標を返すpyautogui.locateCenterOnScreenというのもある

けれど、ある画像ファイルの一部に特定の画像が含まれているから探す関数というのが見当たらない

例えば、次のようなrrScreen.pngというのが保存されていたとして

rrScreen.png

この中にquitBtn.pngが含まれているか(画像ファイルの右下にある)、含まれているならその場所情報を返す、という方法がわからなかった

ソースコードを読んでみた

するとtestのコードに以下のようなのがあるではないか

github.com/asweigart/pyautogui/tests/test_pyautogui.py
        pyautogui.useImageNotFoundException()
        with self.assertRaises(pyautogui.ImageNotFoundException):
            pyautogui.locate("100x100blueimage.png", "100x100redimage.png")
        # Commenting out the locateAll*() functions because they return generators, even if the image can't be found. Should they instead raise an exception? This is a question for pyscreeze's design.
        # with self.assertRaises(pyautogui.ImageNotFoundException):
        #    pyautogui.locateAll('100x100blueimage.png', '100x100redimage.png')        

これか!と思って試してみたらビンゴでした

ptpython
>>> pyautogui.locate('tests/images/quitBtn.png', 'tests/images/rrScreen.png')
Box(left=336, top=844, width=261, height=73)

こうして無事にとってこれました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0