OpenCV Object Detection in Games Python Tutorial #1

preview_player
Показать описание
Learn how to use OpenCV for object detection in video games. This intro tutorial will show you how to install OpenCV for Python and get started with simple image template matching. This will serve as our foundation as we explore many different computer vision techniques in future videos.

0:24 How to install OpenCV
1:45 How OpenCV relates to PyAutoGUI
2:52 How to navigate the OpenCV documentation
4:53 Comparison methods visualized

OpenCV is an open source computer vision library with hundreds of functions for processing and understanding images. In this tutorial, I'm going to show you how to get started with OpenCV in Python by using it to find an image inside another image. This simple form of object detection will be a good starting point before we move on to more advanced image recognition techniques.

The quickest way to get started with OpenCV is: pip install opencv-python

Once installed, you can use the library by importing cv2. Numpy is used extensively when working with OpenCV data, so the top of your Python files will look like this:

import cv2 as cv
import numpy as np

That's all there is for setup. Now let's grab an image we want to process. I'm going to be using this screenshot from Albion Online, but any screenshot will do.

What we're going to do is crop out a small section from our screenshot, save that as a separate image file, and then we're going to use OpenCV to find the position of the smaller image inside our entire screenshot. From my screenshot, I'll crop out one of the cabbages.

The OpenCV function we'll be focusing on is called matchTemplate(). In the documentation, we can see we're going to give this function an image to search over, an image to search for, and a method type for doing the comparison. And we'll end up with a result array. You'll want to experiment with the different comparison methods to see what works best for your use-case.

Alright, let's write some code. The first thing we want to do is load our image files.

The "haystack" image is our screenshot, and we'll be search that for the "needle" image we cropped out. In imread() the first parameter is the image file path, and the second parameter is a flag that allows us to do some pre-processing when loading the images. In this case, we're loading them in unchanged.

Now that we have our images loaded, we can go ahead and call matchTemplate(). I've had good luck using the TM_CCOEFF_NORMED comparison algorithm.

We can quickly see the results from matchTemplate() by displaying that data with imshow().

In imshow(), the first parameter is the window name and the second is the image we want to show. I've also called waitKey() to pause our script while we review the image. Without this, our script would quickly close before we could see the image. Pressing any key on the keyboard will trigger waitKey() to stop waiting, thus ending our script.

In this result image, the bright white pixels represent the positions that best match the cropped image. The black pixels are the worst matches. Note that these best match positions correspond with the upper left corner of where you'd place the needle image.

Now that we've visualized the results of matchTemplate(), let's get those best match coordinates. We can do that using minMaxLoc().

The minMaxLoc() function returns four values. First are the confidence values for the worst and best matches, on a scale from 0 to 1. These are how black or how white the darkest/brightest pixels are in our result image, where 0 would be perfect black and 1 would be perfect white. The last two values minMaxLoc() returns are the positions of those worst/best match pixels in the form of an (X,Y) tuple.

For every needle image that we give matchTemplate(), we will always get back some values from minMaxLoc(), even if that cropped image appears nowhere in the haystack. We can tell when we didn't find a good match because the max confidence value will be low. How low is too low depends on the images you're working with and what you're trying to achieve.

Now that we've found a good match, let's outline where we found it in the haystack image. We can do that using OpenCV's rectangle() function.

Рекомендации по теме
Комментарии
Автор

I just found out your video and even as a senior python and opencv developer I enjoyed watching all of it. Learning image processing through games is an excellent idea. Your presentation is clear and precise, I disagree with comments which states it is a bit boring. Your explanation level is just right for the beginners, not overexplaining things and exploding beginner's minds :D

I wanted to take my time and display my support with a comment because you clearly dedicate your time and enthusiasm to create a helpful content for the community. You just earned a subscriber, keep up the good work my friend.

p.s. About the not so perfect matching score, it is probably due to using jpeg format's lossy compression. After you saved those images as jpeg, they will have very small differences invisible to eye but clearly visible to code as in this example. You might prefer using PNG for lossless image saving or even BMP to get faster image write/read times (high fps).

ilkayatil
Автор

Honestly, the quality of your videos and tutorials is simply astounding. I'm constantly amazed that you don't have hundreds of thousands of subscribers....yet!

wingchangwow
Автор

I'm from Latin America, and I understand your tutorials better than the ones in my language. You're great, thanks

oswaldogerardino
Автор

I was JUST looking up info on this. Who knew it would be from the guy I subbed to from a few days ago. Keep up the good work your putting out unique and great content

mangojango
Автор

Here I was wondering how i was going to pull of object detection, then my man presents the answer to me just like that! Always appreciate you, never fail to expedite my thought process!

setokibah
Автор

Whoever disliked this needs their head checking, this was one of the best programming tutorials I have seen yet.

pollos
Автор

hey i JUST found this channel today, MapleStory is my childhood favorite game so this has motivated me to learn to code and use maplestory as my game, my younger self is screaming right now lol love your content

EvolMe
Автор

This was something I was wondering about,
Thank you. I don't think there are much interactive content like this out there. Glad to have found this channel.
Thank you once again.

Charvin
Автор

why this guy don't have above 100k subs.. he explained it so good. +1

MrFox-ufkv
Автор

I'm on part #3 of your series so far but wanted to revisit this to say - you've been helping me get out of tutorial hell. Thank you so much Ben! You have an amazing teaching style; The documentation and comments along the way in both video & blog posts provides more clarity than other tutorials. Your channel is one of the best out there, please don't stop. Peace.

saint-jiub
Автор

This channel is God sent. Keep going and you'll grow very fast

deusexpersona
Автор

Thanks for the video, I'm from Brazil and here we don't have many good videos about OpenCv and Python
, the simple and objective way you speak is perfect for me who doesn't is a native and thanks for not using so many slangs

knightwithouthorse
Автор

this channel is so much underrated.Very good content bro, keep it up

teslar
Автор

It took two years but I am very happy that I managed to find your channel! Thank you for the great tutorials and videos

eliotbicak
Автор

Nice to see you taking it to the next level

Joshua-krfq
Автор

God I love you and this series, the quality content we all need but do not deserve

hansenliu
Автор

this guy should get more subscribers!
thank you for the great contents

thedeveloper
Автор

Open CV is great no denying but the library is just huge, it's full of functions to do all
sorts of thing, this is a great advantage(keeps ur code short and neat) and disadvantage
( I really find it difficult to remember these lol)
like think about it for a sec, there is function for like literally everything and parameters which makes no sense
for newbies (like me myself), but nevertheless great video mate, really liked how u walked through
the documentation (encouraging viewers to explore) and explained as much as possible while writing
the code and made the video as short as it possibly could have been u certainly deserve more subs
and recognition mate :)

angelsdemons
Автор

Hi there Ben!

I stumbled upon your channel because I wanna learn how to code.

I watched this video to see if it interests me though I don't have any knowledge yet. But boy! You explain things so well that I get the idea of what you are doing.

I am glad I've found your channel.

+1 sub!

alchercananea
Автор

print("Hello from Brazil")

Thx bro

VersusBR