如何使用OpenCV在同一imshow上显示多个对象检测?

2024-04-25 06:07:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我的(示例)代码检测两个图像,并在单独的cv.imshow窗口上逐个显示它们。一旦我按下我的waitKey,我希望它们显示在同一个cv.imshow上,其思想是我希望能够在需要时传递不同的对象以进行检测

我想documentation会说waitKey(0)会暂停视频循环waitKey(1)会暂停视频循环1毫秒,然后继续从我的输入中读取帧,在这种情况下,imageGrab

我想我误解了一些东西,因为来自imageGrab的视频循环确实继续1,它仍然在单独的窗口上显示检测,只有在按下Q后才移动到第二个检测

如何使这两个对象都显示在一个im.show

import pyautogui as py
import glob
import cv2 as cv
from PIL import ImageGrab
import numpy as np
import pygetwindow

s = glob.glob(r"C:\a\*.png")
p = glob.glob(r"C:\b\*.png")

# Load Images 
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append(img)
    return image_list

def drawRectangle(image_list):
    # Video Loop
    while True:
    # Grab Window and find size 
        window = pygetwindow.getWindowsWithTitle('Steam')[0]
        x1 = window.left
        y1 = window.top
        height = window.height
        width = window.width
        x2 = x1 + width
        y2 = y1 + height
        # Actual Video Loop, cropped down to the specific window,
        # resized to 1/2 size, and converted to BGR for OpenCV
        haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
        (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
        haystack_img_resized = haystack_img.resize((width, height))
        haystack_img_np = np.array(haystack_img_resized) 
        haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
        
        # Object Detection
        for i in image_list:
            needle_img = i
            result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)
    
            # Get the best match position
            min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
            print(max_val)

            # Define top left and bottom right
            (H, W) = i.shape[:2] 
            top_left = max_loc
            bottom_right = (top_left[0] + W, top_left[1] + H)
            
            # Highlight Detection
            threshold = 0.9
            if max_val >= threshold:
                cv.rectangle(haystack, top_left, bottom_right, 255, 2)

        cv.imshow("Screen", haystack)
        if cv.waitKey(1) == ord('q'):
            cv.destroyAllWindows()
            break


s = loadImages(s)
p = loadImages(p)

drawRectangle(s)        
drawRectangle(p)

enter image description here

enter image description here