Есть ли способ сравнить два изображения, если одно из них содержится в другом

#python #image-processing

#python #обработка изображений

Вопрос:

Хорошо, проблема в том, что я не могу сравнить 2 изображения вместе, одно из которых является шаблоном, «большим изображением», а другое — его объектом. метод find_image взят из Интернета, поэтому я все еще не уверен, как именно с ним работать, но ошибка гласит, что. Идея программы состоит в том, чтобы проверить, есть ли на скриншоте «объект», и если есть, получить координаты и заставить мышь щелкнуть по нему.

 Traceback (most recent call last):
  File "C:/Users/thero/Desktop/Idling bot/code.py", line 97, in <module>
    main()
  File "C:/Users/thero/Desktop/Idling bot/code.py", line 93, in main
    find_image(os.getcwd(r'C:UserstheroDesktopIdling botfull_pic.png'), os.getcwd(r'C:UserstheroDesktopIdling botfull_pic.png'))
TypeError: getcwd() takes no arguments (1 given)

import win32api, win32con
from PIL import ImageGrab, ImageOps, Image
import os
import glob
import time
from numpy import *
import numpy as np
import cv2

image_list = []
for filename in glob.glob(r"C:UserstheroDesktopIdling bot*.png"):
    im = Image.open(filename)
    image_list.append(im)
    print("results : "   str(filename))


# Globals
# ------------------
x_pad = 158
y_pad = 256
image_name = ""


def screenGrab():
 box = (x_pad 1, y_pad 1, x_pad 962, y_pad 542)
 im = ImageGrab.grab(box)
 im.save(os.getcwd()   '\full_pic' '.png', 'PNG')
 return im

def leftClick():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
    time.sleep(.1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)
    print("Click.")

def leftdown():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    time.sleep(.1)
    print("left Down")


def leftUp():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
    time.sleep(.1)
    print("left release")


def mousePos(cord):
 win32api.SetCursorPos((x_pad   cord[0], y_pad   cord[1]))

def get_cords():
  x,y=win32api.GetCursorPos()
  x=x-x_pad
  y=y-y_pad
  print(x,y)

# def compareImg():
#  image1=cv2.imread(r'C:UserstheroDesktopIdling botCopper.png')
#  image2=cv2.imread(r'C:UserstheroDesktopIdling botfull_pic.png')
#
#  difference = cv2.subtract(image1,image2)
#  result = not np.any(difference)
#  if result is True:
#   print ("they are the same")
#  else:
#   cv2.imwrite(("result.jpg",difference))
#   print ("Different")

def find_image(im, tpl):
    im = np.atleast_3d(im)
    tpl = np.atleast_3d(tpl)
    H, W, D = im.shape[:3]
    h, w = tpl.shape[:2]

    # Integral image and template sum per channel
    sat = im.cumsum(1).cumsum(0)
    tplsum = np.array([tpl[:, :, i].sum() for i in range(D)])

    # Calculate lookup table for all the possible windows
    iA, iB, iC, iD = sat[:-h, :-w], sat[:-h, w:], sat[h:, :-w], sat[h:, w:]
    lookup = iD - iB - iC   iA
    # Possible matches
    possible_match = np.where(np.logical_and.reduce([lookup[..., i] == tplsum[i] for i in range(D)]))

    # Find exact match
    for y, x in zip(*possible_match):
        if np.all(im[y 1:y h 1, x 1:x w 1] == tpl):
            return (y 1, x 1)

    raise Exception("Image not found")
def main():
 screenGrab()
 find_image(os.getcwd(r'C:UserstheroDesktopIdling botfull_pic.png'), os.getcwd(r'C:UserstheroDesktopIdling botfull_pic.png'))
 get_cords()

if __name__ == '__main__':
  main()
 

Комментарии:

1. Пожалуйста, напишите более конкретное название вопроса и просто включите детали конкретной проблемы в сам вопрос.

2. Попытался объяснить это немного лучше. Извините, если это все еще плохо.

Ответ №1:

Как указано в трассировке, get_cwd() не принимает параметры. Эта функция просто получает текущую работу напрямую. Я не слишком углублялся в код, но если find_image сравнивает изображения, просто попробуйте это вместо:

 def main():
 screenGrab()
 find_image('C:UserstheroDesktopIdling botfull_pic.png', 'C:UserstheroDesktopIdling botfull_pic.png')
 get_cords()
 

Комментарии:

1. « Трассировка (последний последний вызов): файл «C:/Users/thero/Desktop/Idling bot/code.py «, строка 97, в файле <module> main() «C:/Users/thero/Desktop/Idling bot/code.py «, строка 93, в главном find_image(r’C:UserstheroDesktopIdling ботfull_pick.png’, r’C:UserstheroDesktopIdling ботCopper.png’) Файл «C:/Users/thero/Desktop/Idling bot/code.py «, строка 76, в find_image sat = im.cumsum(1).cumsum(0) Ошибка типа: невозможно выполнить накопление с гибким типом « теперь ошибка изменилась: D

2. Поэтому вам нужно будет продолжить отладку. Теперь найдите решение этой ошибки типа «, «невозможно выполнить накопление с помощью гибкого типа». Добро пожаловать в coding!