《python + opencv实现目标检测》

发布时间 2023-03-27 17:52:27作者: 一个不知道干嘛的小萌新

1.环境安装

1.1 安装python

  python版本是3.10

  安装 Python:首先需要安装 Python,可以从官网 https://www.python.org/downloads/ 下载安装包,选择最新版本的 Python 安装即可。
  在终端输入python,看是否报错,没报错证明python安装成功。

1.2 安装opencv

  在终端输入:

pip install numpy
pip install opencv-python

测试是否安装成功

python
>>> import cv2

  没有报错,证明成功。

1.3 安装后续需要用到的库

pip install datetime
pip install pygame
pip install keyboard
pip install pywin32
pip install pyautogui
pip install Pillow

 

2.简单的源码

# -*- coding: utf-8 -*-
import cv2
import numpy as np
import time
import pyautogui
import keyboard
import sys
import pygame
import datetime
import os

#窗口位置
game_rect = (0, 0, 800, 600)  

#需要检测的目标
myself_template = cv2.imread('myself.png', cv2.IMREAD_GRAYSCALE)
wheel_template = cv2.imread('wheel.png', cv2.IMREAD_GRAYSCALE)
other_template = cv2.imread('other.png', cv2.IMREAD_GRAYSCALE)

#check_green_template = cv2.imread('check_green.png', cv2.IMREAD_GRAYSCALE)
player_time = 0

#音乐相关初始化
pygame.init()
pygame.mixer.music.load('childhood.mp3')


#切换窗口
def exit_game():
    keyboard.press('alt')
    time.sleep(0.1)
    keyboard.press('tab')
    time.sleep(0.1)
    keyboard.release('alt')
    time.sleep(0.1)
    keyboard.release('tab')
    #退出整个程序
    sys.exit()

def play_audio():
    if not pygame.mixer.music.get_busy():
        pygame.mixer.music.play()

while True:
    #屏幕截图加载图片
    screenshot = pyautogui.screenshot(region=game_rect)
    screenshot = np.array(screenshot)
    screenshot = screenshot[:, :, ::-1].copy()
    screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)

    #获取当前时间
    current_time = datetime.datetime.now()
    print(f"[{current_time}] ")


    #轮检测
    wheel_result = cv2.matchTemplate(screenshot_gray, wheel_template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.99
    hole_loc = np.where(wheel_result >= threshold)
    num_matches = len(hole_loc[0])
    if num_matches > 0:
        print(u"检测到地图轮个数为:",f"{num_matches}")
    '''if num_matches == 1:
        exit_game() '''          

    #测谎检测
    '''check_green_result = cv2.matchTemplate(screenshot_gray, check_green_template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.99
    other_loc = np.where(check_green_result >= threshold)
    num_matches = len(other_loc[0])
    if num_matches > 0:
        print(u"检测到测谎仪:",f"{num_matches}")'''
    for filename in os.listdir('check_folder'):
        if filename.endswith('.jpg') or filename.endswith('.png'):
            check_img = cv2.imread(os.path.join('check_folder', filename), cv2.IMREAD_GRAYSCALE)
            check_result = cv2.matchTemplate(screenshot_gray, check_img, cv2.TM_CCOEFF_NORMED)
            threshold = 0.97
            other_loc = np.where(check_result >= threshold)
            num_matches = len(other_loc[0])
            if num_matches > 0:
                print(u"检测到测谎仪:",f"{num_matches}")
                play_audio()
                

    #其他玩家检测
    other_result = cv2.matchTemplate(screenshot_gray, other_template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.99
    other_loc = np.where(other_result >= threshold)
    num_matches = len(other_loc[0])
    if num_matches > 0:
        player_time += 1;
        if player_time > 5:
            player_time = 0
            print(u"检测到其他人进入地图人数为:",f"{num_matches}")
            play_audio()
    else:
        player_time = 0


    #自己检测
    myself_result = cv2.matchTemplate(screenshot_gray, myself_template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.99
    myself_loc = np.where(myself_result >= threshold)
    num_matches = len(myself_loc[0])
    if num_matches > 0:
        print(u"检测到我自己人数:",f"{num_matches}") 

    time.sleep(1)

  该demo需要识别的图片以及目标图片以及mp3音源,因此直接复制是跑不了的。本demo是提供一个思路。