Поиск изображения в другом изображении [opencv error -209] - PullRequest
0 голосов
/ 11 июля 2019

Код ищет изображение на другом изображении и выводит координаты.

  1. Снимок экрана создается и сохраняется как изображение в переменной
  2. Любое изображение сохраняется как изображение в переменной
  3. Анализируются размеры изображений
  4. Изображения преобразуются в оттенки серого (8 бит)
  5. преобразуются (* 2.) Изображение в массив онемения преобразуется
  6. вцикл по координатам (x, y) снимок экрана (с обрезанным снимком экрана) сравнивается с размером искомого изображения и сравнивается со снимком экрана ... если они совпадают, координаты будут выведены, программа завершится
    • 6 координаты обновлены (с другими условиями программа также может быть прервана здесь, потому что, например, координаты в некоторой точке за пределами изображения могут быть)

Проблема: * (когда массивы имеют одинаковый размер и одинаковое количество каналов) (сообщение об ошибке ..) ... но изображения имеют одинаковый размер и имеют оба 8 бита ..?

import pyautogui
import numpy as np
import cv2
from PIL import Image

def screenshot():
    screenshot = pyautogui.screenshot()
    return screenshot

def checkImgEqual(npArray1, npArray2, width, height):

    difference = cv2.absdiff(npArray1, npArray2)

    if cv2.countNonZero(difference) / (width*height / 100) < 1:
        return True
    else:
        return False

def searchImg(sought_after, image):

    # set widths, heights, x and y
    width_image, height_image = image.size
    width_sought_after, height_sought_after = sought_after.size
    x = y = 0

    # change to grayscale image
    sought_after = sought_after.convert('L')
    image = image.convert('L')

    sought_after = np.array(sought_after) # create numpy array

    while True:

        cycle = 0
        print(cycle)
        cycle += 1

        # crop image
        area = (x, y, width_sought_after, height_sought_after)
        cropped_img = image.crop(area)

        cropped_img = np.array(cropped_img) # create numpy array

        # check if current location (x, y) is sought_after
        if checkImgEqual(cropped_img, sought_after, width_sought_after, height_sought_after):
            print(x, ",", y)
            break

        # update current location
        x += 1

        if x + width_sought_after >= width_image:

            if y + width_sought_after <= height_image:
                x = 0
                y += 1
            else:
                print("image not found!")
                break

img1 = Image.open("logo.png")
img2 = screenshot()
searchImg(img1, img2)
0
0
Traceback (most recent call last):
  File ".../findImg.py", line 63, in <module>
    searchImg(img1, img2)
  File ".../findImg.py", line 45, in searchImg
    if checkImgEqual(cropped_img, sought_after, width_sought_after, height_sought_after):
  File ".../findImg.py", line 12, in checkImgEqual
    difference = cv2.absdiff(npArray1, npArray2)
cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:663: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'cv::arithm_op'

Process finished with exit code 1

.. также я ожидаю, что выход 0 числа для каждого цикла, поставить фактическое два "0"?

...