在其他图像中搜索图像[opencv错误-209]

时间:2019-07-11 18:38:16

标签: python numpy opencv python-imaging-library

代码在另一张图片上查找图片并输出坐标。

  1. 屏幕截图已创建并保存为变量中的图像
  2. 任何图像都保存为变量中的图像
  3. 分析图像大小
  4. 图像被转换为​​灰度(8位)
  5. 已转换(* 2)。图像已转换为numby数组
  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”吗?

0 个答案:

没有答案