Thresholding with Match Template - OpenCV Object Detection in Games #2

  Рет қаралды 87,652

Learn Code By Gaming

Learn Code By Gaming

Күн бұрын

Detect multiple objects with OpenCV's match template function by using thresholding. In this tutorial, we dig into the details of how this works.
Full tutorial playlist: • OpenCV Object Detectio...
GitHub Repo: github.com/lea...
OpenCV documentation: docs.opencv.or...
Official template matching tutorial: docs.opencv.or...
1:18 Understanding the result from matchTemplate()
2:25 Using the debugger in VSCode
5:08 Why is the match template result smaller than the original image?
6:18 Using numpy where() to filter the results
7:27 Converting np.where() to a list of pixel positions
9:41 Adjusting the threshold
10:11 Drawing multiple rectangles
12:27 Using TM_SQDIFF_NORMED
With thresholding, we can detect multiple objects using OpenCV's matchTemplate() function. They discuss briefly how to do this in the offical tutorial, but here I will cover it more in-depth.
Previously we used minMaxLoc() to get the best matching position for our needle image, but matchTemplate() actually returns a result matrix for all the positions it searched.
Each value in this matrix represents the confidence score for how closely the needle image matches the haystack image at a given position. The index of the outer dimension represents the Y position, and the index of the inner list represent the X position. For example, the confidence value 0.58679795 in the data [see: learncodebygam...] corresponds to Y = 1 and X = 6. When we overlay the needle image on the haystack image, such that the upper left corner of the needle is placed at pixel position (6, 1), it's match score is 0.58679795.
Note that the resulting matrix size is (haystack_w − needle_w + 1) * (haystack_h − needle_h + 1). This is because there are no meaningful match results when the needle image is partially overhanging the haystack image.
The idea with thresholding is, we want to get the coordinates of all the places where the match confidence score is above some threshold number that we set.
To do that, the documentation suggests we should use the np.where() function. This will give us all the locations above that threshold.
In the result, the first array contains the Y positions, and the second contains the X positions. So in the above example we found two matches above the threshold we set, at positions (1, 1) and (15, 5).
So we have the data we need know, but the format returned by np.where() isn't very convenient to work with. So lets convert it to a list of (X, Y) tuples: list(zip(*locations[::-1]))
In this line of code, [::-1] reverses a numpy array, so that we get the X values to come before the Y. Then the star * unpacks a list, so that we now have two one-dimensional arrays instead of one two-dimensional array. We then use zip() to merge those two lists into a bunch of new lists, each comprised of the elements from the input lists that share the same index. And because zip() actually returns a generator instead of a rendered list, we wrap it all in list() to get the final result we're looking for.
So that's how we've converted the Y and X arrays returned by np.where() into a list of (X, Y) tuples.
Now that we have a list of matching locations, let's draw rectangles around all of those locations. We'll adapt our code from part 1 to do this, and simply loop over all the locations.
Keep adjusting your threshold, and your comparison method, until you get as many correct matches as possible without any false positives. In this case, I achieved the best result by using cv.TM_SQDIFF_NORMED and setting a threshold of values below 0.17 (remember TM_SQDIFF_NORMED uses inverted results).
You'll no doubt notice that you are getting many more location results than the number of rectangles you're seeing on the result image. You'll also notice that some of the rectangles are much thicker than others. This indicates that you're getting many match results that are very close to one another, and your rectangles are overlapping each other.
Visually this may not be too problematic, but if you're trying to count up the number of some item in an image, or if you're searching for screen locations to click on, then you'll need some way to clean this up. And that's what we'll be covering in part 3 of this tutorial: how to group those overlapping rectangles into single detection results.
Read the full written tutorial here: learncodebygam...

Пікірлер: 120
@AlexTubu
@AlexTubu 4 жыл бұрын
At first I thought that I just wanted to cheat on the game. Then I saw your video. Then I saw the future. And now I know that game will be only the first step for me in this story.
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Watch out, the coding might be more fun than the games themselves 😄
@gmac9313
@gmac9313 3 жыл бұрын
And how it's going now?
@Гусьэкономит
@Гусьэкономит Жыл бұрын
It has been two years already, where is the continuation? Why did you abandon your channel? You explain better than all my teachers! You're the best! It has been 2 years already, perhaps you have improved object detection, bot performance, and their movement between points, or maybe there's something else interesting to see!
@spencer5028
@spencer5028 Ай бұрын
Got hired by DoD
@patwicker1358
@patwicker1358 4 жыл бұрын
Just discovered your channel and am enjoying it very much. I really like your presentation style, the fact that you show manual pages, and that you know what you are going to say with no fumbling.
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
That's the style I'm going for. Glad you like it!
@zen123w
@zen123w 4 жыл бұрын
great explanation of zip(*location[::-1]). Being some what familiar with opencv, I have never come across such a clear explanation of that line before.
@cidsantiago9577
@cidsantiago9577 3 жыл бұрын
I am learning opencv because I love to automate tasks and I love to play online games and I have to say your channel blows my mind. I watch and re-watch all of your videos. It have been AWESOME learn with you, thank you very much spending time teaching us all.
@Charvin
@Charvin 4 жыл бұрын
I have been waiting for this part very eagery, and it was worth the wait. My test script was able to identify objects I show on an image. There is a sense of great satisfaction when you see something you made work. Figuring out just the right threshold where the program can find out things quite right was the part which took a bit of time & lots of trial and error (understandable). Really glad that it worked out. Thank you! Looking forward to learning from the next videos in the series as well as from the old ones on the channel.
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Thanks, glad to hear you're following along!
@pacman804
@pacman804 2 жыл бұрын
I love you style of teaching so much, hands down one of my best programming channels.
@thedeveloper643
@thedeveloper643 4 жыл бұрын
i've waited for the next tutorial since the first one and here it is! thank you so much for valuable contents
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Thanks, glad you look forward to these!
@JS-kr7zy
@JS-kr7zy 4 жыл бұрын
super excited for this style of tutorial. Project centered learning is definitely the way to go, and there isn't enough.. I don't want to say "hand-holdy" content, but after you get to a certain point programming kind of takes a leap off the diving board into dense documentation.
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Yeah for sure. I try to lead people to the fun stuff so they're more excited to explore on their own from there.
@greedsloth1516
@greedsloth1516 4 жыл бұрын
Glad to have found this channel! Keep up the good work Ben! Stay safe amidst of the pandemic
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Thanks, you too! Thanks for checking out my videos.
@laboratoriya
@laboratoriya 3 жыл бұрын
Perfect tutorial. This gentleman explains everything crearly.
@DemandRS
@DemandRS 2 жыл бұрын
First time I've seen unpacking with *, really cool. Good video thanks :)
@SquallHart05
@SquallHart05 2 жыл бұрын
You're an EXCELLENT teacher. Thank you!
@yunustalhaerzurumlu6547
@yunustalhaerzurumlu6547 Жыл бұрын
Dude your channel is amazing, your presentation is really clear, Keep up with the good work!
@alekaditez3830
@alekaditez3830 3 жыл бұрын
some of the best python tutorials out there. Much appreciated and good luck to you!
@LearnCodeByGaming
@LearnCodeByGaming 3 жыл бұрын
Thanks, glad you like them!
@nerdwolf3839
@nerdwolf3839 3 жыл бұрын
Never stop making videos. Your videos are amazing!!!
@ProficusLets
@ProficusLets 3 жыл бұрын
Спасибо за прекрасные уроки дружище!
@emiletheroux2317
@emiletheroux2317 10 ай бұрын
Trying for Path of exile, its hard but your lessons helps a lot.
@tobias6361
@tobias6361 4 жыл бұрын
Amazing that you try that on an Albion screenshot and what a coincidence that I’m using template matching for an Albion project too :D
@MrBru96
@MrBru96 4 жыл бұрын
Great video! I look forward to seeing this kind of object detection into a real time video. Keep it up!
@vakula6859
@vakula6859 3 жыл бұрын
Ты делаешь очень крутые вещи для очень привычных, для многих, занятий. Большое тебе спасибо! You do very cool things for very familiar, for many, activities. Thank you very much!
@markr87
@markr87 2 жыл бұрын
Just came across your videos recently and I have to say you are amazing! I have been trying to learn programming for nearly a decade but it never really grabbed my attention, and totally lost by the time i got to object oriented programming. First time ever I am actually enjoying the lessons. Subbed and crunching through all your videos!
@keve8586
@keve8586 4 жыл бұрын
you are the man! thank you for your content and channel!
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Thanks, glad you like it!
@faizaanazam
@faizaanazam 3 жыл бұрын
Excellent series so far. Thanks, Ben!
@prodffstarboy
@prodffstarboy Жыл бұрын
lovely ! trying to build a bot for a mobile RPG game emulated on Bluestacks, this has been a great help !
@prodffstarboy
@prodffstarboy 9 ай бұрын
@Xarius01 what do you wanna know
@shamelessvideoeditor3839
@shamelessvideoeditor3839 2 жыл бұрын
great video, thank you buddy. Looking forward to running through some of your other videos.
@goob6433
@goob6433 4 жыл бұрын
Man this is funny I actually came to your channel with the pyautogui video hoping to code a fishing bot for Albion online, and look what I see! A tutorial for harvesting cabbages
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Haha, nice coincidence!
@palette454
@palette454 4 жыл бұрын
you saved me so many work hours with openCV
@javiermusso3010
@javiermusso3010 2 жыл бұрын
Hey, really enjoy your style in this videos! Keep it up and thanks a lot!
@ЕвгенийСергеевич-л7с
@ЕвгенийСергеевич-л7с 3 жыл бұрын
Всех приветствую! Бен большое спасибо тебе за твой труд! В русском сегменте ютубу, к сожалению довольно мало именно прикладного использования Opencv, информация подается в виде поверхностного ознакомления. Еще раз тебе спасибо!
@ЕвгенийСергеевич-л7с
@ЕвгенийСергеевич-л7с 3 жыл бұрын
Greetings to all! Ben thank you so much for your hard work! In the Russian segment of KZbin, unfortunately, there is quite a little application use of Opencv, the information is provided in the form of a superficial acquaintance. Thank you again!
@ProficusLets
@ProficusLets 3 жыл бұрын
Полностью согласен с тобой!
@leonardochaves6569
@leonardochaves6569 4 жыл бұрын
thanks for the content. It was everything I was looking for. You even got the game right that I would like to make a bot.
@ColeDockter-g1t
@ColeDockter-g1t Жыл бұрын
Would love to see a breakdown of diablo 2's pixel bot, which is coded in python & uses this library. Hope there are more of these!!
@cedricdeege5763
@cedricdeege5763 4 жыл бұрын
Thanks man, really clear and easy to follow!
@Alexander_Meyer
@Alexander_Meyer 4 жыл бұрын
Cant wait for the next episode :D
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Next video is up!
@tymothylim6550
@tymothylim6550 4 жыл бұрын
Hello Ben! Thank you for this video! I think the explanations were clear.
@aidancohen8721
@aidancohen8721 4 жыл бұрын
I love these videos. thanks so much these are great!
@svampebob007
@svampebob007 4 жыл бұрын
Really interesting and nice explanation. I find that using games to learn how to program is a really neat way to learn the basics of a program. Mainly because you are already familiar with the game, but also because there's 1000 different things to "program" for in a game. I started with programing a rocket guidance system in KSP by using KOs, but also it made me learn more about Bash and SSH since I was running KSP over the network and I used SSH to connect to the game "telnet console". I'm going to hell for this one but: One eye on the code, one eye on the console :)
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Yeah the project ideas with games are endless, which is great for beginners because it helps you get a lot more time writing code. Kerbal Space Program is fun, haven't played it in years!
@JordhanRDZ
@JordhanRDZ 4 жыл бұрын
Amazing series ! Can you give some spoiler for the next episodes? xD
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Thanks! Part 3: Grouping rectangles and calculating mid/click points. Part 4: Fast real-time image capture. Part 5: Real-time object detection. Part 6: Image processing for better match results. Part 7: Integrating automated clicks and bringing it all together. Might be a few parts past that, too.
@irynashevchenko1575
@irynashevchenko1575 3 жыл бұрын
incredible !! super!!! great work!!!
@martinneff1681
@martinneff1681 4 жыл бұрын
Great Tutorial, Thanks
@lordraphi
@lordraphi 4 жыл бұрын
Waiting for the next one
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Next one is up!
@falsemessiah5515
@falsemessiah5515 3 жыл бұрын
keep doing this! ive learned alot
@jayadevashok2070
@jayadevashok2070 4 жыл бұрын
Awesome tutorial bro!!!
@DanielXavierDosReis
@DanielXavierDosReis Жыл бұрын
awesome good! very nicee lesson, bro, keep it up, very well explained
@MrRAk1N
@MrRAk1N 2 жыл бұрын
Have you considered making a comparison using YOLO?
@Natsumi_Nakamura
@Natsumi_Nakamura Жыл бұрын
[spanish] 2023 y me ayudas un monton con todo esto. lo usare para programar bots >:D . I♥U so much
@waynewu7763
@waynewu7763 3 жыл бұрын
thanks alot for these tutorials. I am also learning as I follow along slowly. I have a question, for your for loop, would it be possible (or easier) to compact into a list comprehension? if so, how would that work?
@rb_420
@rb_420 2 жыл бұрын
you are amazing!! thanks for sharing so much knowlodge (:
@Backflipmarine
@Backflipmarine 4 жыл бұрын
Can you use multiple images or is that more tensorflow? Whens the next vid btw?
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
You can search for multiple images, but it starts getting slow pretty fast in my experience. I filmed the next video earlier today, so I should be done editing and have it uploaded in 2-3 days.
@dr.kingschultz
@dr.kingschultz 3 жыл бұрын
Thank you for the videos!
@kosmonautofficial296
@kosmonautofficial296 Жыл бұрын
Great video! Thank you for this great tutorial I. I am hoping to use this for detecting what round I am on in nazi zombies.
@TravisJMedia
@TravisJMedia 4 жыл бұрын
Amazing, thanks for your tuts! Can you show us an example on how to use opencv to let the bot detect when the bot reaches the edge of a zone? I'm trying to let my bot gather resources by walking randomly and with an unstuck feature. Only challenge is that he keeps getting stuck at the edge of the map.
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
What game?
@TravisJMedia
@TravisJMedia 4 жыл бұрын
@@LearnCodeByGaming Albion
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
@@TravisJMedia Cool, I'll see if I can find a solution for that and include it in a future video.
@TravisJMedia
@TravisJMedia 4 жыл бұрын
@@LearnCodeByGaming Thanks a lot man! You're the best.
@thewdead3673
@thewdead3673 Жыл бұрын
Hey, Great tutorial! Is it possible for you to make some tutorial on how to walk your character in in a defined square? I am trying to make a bot for pokemon game farming in grass and I am not sure how to move my character in the same area without it going to the wrong way. Thanks!
@waenurdeanwaehamad2787
@waenurdeanwaehamad2787 10 ай бұрын
I wonder why does it have to reverse the locations, does it mean that np.where() returns the array of ys first then xs?
@t-72k16
@t-72k16 4 жыл бұрын
Thank you so much for these, i was wondering if you can go into some better object detection that can handle camera angle changes in game?
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Yeah that does get tricky when the camera angles change. I'm going to be covering more and more advanced topics as this series continues.
@t-72k16
@t-72k16 4 жыл бұрын
@@LearnCodeByGaming using the other technique of for looping through each pixel and seeing if it matches a color on a list. It works pretty well but can be slow at times
@nburn8306
@nburn8306 4 жыл бұрын
I ran into a problem with the code example at 10:23. When running that in VS Code my CPU usage spiked, the program took 5-10 minutes to finish, and the image result was different from the one in the video. For anyone having this example freeze up on them, the issue for me seemed to be calling "cv.waitKey()" with no argument (line 35). After changing "cv.waitKey()" to "cv.waitKey(0)" the code ran in a fraction of the time and produced the expected image result.
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Thanks for pointing that out! From video 4 I started using cv.waitKey(1) myself. I don't recall why I made the switch, but I probably ran into problems, too.
@nburn8306
@nburn8306 4 жыл бұрын
@@LearnCodeByGaming Weird, I just went to double check and can't recreate the bug anymore. waitKey now works even without an argument. Some "magic smoke" stuff going on in my computer...
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
@@nburn8306 Oh man that'll drive you crazy. Glad it works I guess?
@magnumdavid6394
@magnumdavid6394 Жыл бұрын
Thank you!
@SpieltGames
@SpieltGames 3 жыл бұрын
Why do you have a black left eye, did you have any blows?
@kevinflynn4867
@kevinflynn4867 Жыл бұрын
Awesome !
@andreasas1462
@andreasas1462 4 жыл бұрын
nice project dude
@venkateshvenky5489
@venkateshvenky5489 4 жыл бұрын
Can we able to detect multiple objects of by giving two different sample templates
@LearnCodeByGaming
@LearnCodeByGaming 4 жыл бұрын
Yes, absolutely!
@venkateshvenky5489
@venkateshvenky5489 4 жыл бұрын
@@LearnCodeByGaming Could you please tell me how to give input to it.Thanks in advance
@Magistrmate
@Magistrmate Жыл бұрын
Спасибо за видео!
@AntonVasilev-q3t
@AntonVasilev-q3t 9 ай бұрын
KOOOOOOOOOOOL!!!!!!!! THANKS!!!!!!!!!!!!!!!!!!
@airidasrom583
@airidasrom583 2 жыл бұрын
it opens for me like 4 windows and in the last it only shows all the images im searching tho after i close same image with same marked sports appear.. any fix ? or its suppose to be like that ?
@jcorrify
@jcorrify 10 ай бұрын
Using python 3.12 and opencv python 4.8.1 and the result format look different in my debugger, I can't scroll through results
@MultiBelz
@MultiBelz 2 жыл бұрын
very cool thank you
@locutusvonborg2k3
@locutusvonborg2k3 2 жыл бұрын
ok, i do have the problem, that a result, which is false, has a higher confidence value, than what i am looking for, so i cant set the threshold higher, cause then i dont get what i want. however, my object im looking for isnt static, its kinda a moving gif xD still very nice videos so far, learned a lot
@ismaelRR
@ismaelRR 3 жыл бұрын
Your are a boss!!!!!
@whxmpy56
@whxmpy56 2 жыл бұрын
Matchtemplate thing does not work comes up with this (-215:Assertion failed) _img.size().height
@wolfpackgaming2571
@wolfpackgaming2571 4 ай бұрын
what settings do you use in vs code?
@nguyenhungiot
@nguyenhungiot Жыл бұрын
Hello, I,m using openCV to play game Mir4 automate by detect quests in game, please help me some idea! Thank you very much
@kuhicop
@kuhicop 2 жыл бұрын
For some reason, sometimes it will return a full black image when calling the WinCap.get_screenshot() method. I have to keep restarting the game and visual studio until it works again. Someone figured out this?
@siman211
@siman211 3 жыл бұрын
I have Pycharm so can't run and debug i tried to get visual code but can't make it to install opencv on it don't know why I am new to coding i try a lot of site codeacadamy, pirple but i just can't still learn you somehow manage to explain a little better then others i hope i manage to learn something from you
@diegogutierrez5989
@diegogutierrez5989 2 жыл бұрын
Thanks 👍👍👍
@Egeevis
@Egeevis 5 ай бұрын
thanks a lot
@matheuskjn
@matheuskjn 4 жыл бұрын
Conteúdo muito bom
@onggiachoigame4929
@onggiachoigame4929 3 жыл бұрын
I use your code: threshold = 0.85 locations = np.where(result >= threshold) print(locations) # the np.where() return value will look like this: # (array([1, 5], dtype=int32), array([1, 15], dtype=int32)) and this is my result: (array([483], dtype=int32), array([514], dtype=int32)) please help me.
@Alex_Aly
@Alex_Aly 3 жыл бұрын
Does anybody know a scale-invariant Template Matching method ?
@vitustiberius2645
@vitustiberius2645 3 жыл бұрын
try out the python plugin and use the '# %%' code block to run python interactive cell
@hamburgerhamburger986
@hamburgerhamburger986 2 жыл бұрын
My code draws 5-10 lines for every object for some reason
@sobrelaroca2701
@sobrelaroca2701 3 жыл бұрын
Emm bro. I love you
@EranM
@EranM 3 жыл бұрын
9:20 I think theres a thing called "Transpose" Which is much more intuitive and readable
@aminghasembeigi7078
@aminghasembeigi7078 2 жыл бұрын
commenting for the algorithm
@pastuh
@pastuh 3 жыл бұрын
And peoples think Diablo Resurrected will not have bots :X
@dedpihto680
@dedpihto680 2 жыл бұрын
it couldn't even select all the required objects without garbage
@CyberZyro
@CyberZyro 3 жыл бұрын
its way more easier with cascade files
@leingod7779
@leingod7779 Жыл бұрын
trying to make a BOT for a game :D
Grouping Rectangles into Click Points - OpenCV Object Detection in Games #3
14:02
Fast Window Capture - OpenCV Object Detection in Games #4
30:48
Learn Code By Gaming
Рет қаралды 237 М.
Сюрприз для Златы на день рождения
00:10
Victoria Portfolio
Рет қаралды 1,3 МЛН
Help Me Celebrate! 😍🙏
00:35
Alan Chikin Chow
Рет қаралды 82 МЛН
My Daughter's Dumplings Are Filled With Coins #funny #cute #comedy
00:18
Funny daughter's daily life
Рет қаралды 27 МЛН
Зу-зу Күлпаш 2. Дартс
41:09
ASTANATV Movie
Рет қаралды 431 М.
HSV Color Range Thresholding - OpenCV Object Detection in Games #6
22:48
Learn Code By Gaming
Рет қаралды 50 М.
Training a Cascade Classifier - OpenCV Object Detection in Games #8
32:29
Learn Code By Gaming
Рет қаралды 154 М.
I tried to make a Valorant AI using computer vision
19:23
River's Educational Channel
Рет қаралды 1,5 МЛН
Blazingly Fast Greedy Mesher - Voxel Engine Optimizations
23:35
OpenCV Object Detection in Games Python Tutorial #1
14:30
Learn Code By Gaming
Рет қаралды 271 М.
Dear Game Developers, Stop Messing This Up!
22:19
Jonas Tyroller
Рет қаралды 718 М.
@PirateSoftware  explains kernel level anticheat
4:52
DJSuperPanda
Рет қаралды 61 М.
Faster than Rust and C++: the PERFECT hash table
33:52
strager
Рет қаралды 581 М.
I made OD bots for Gaming in 30 MINUTES
1:13:33
Nicholas Renotte
Рет қаралды 25 М.
Сюрприз для Златы на день рождения
00:10
Victoria Portfolio
Рет қаралды 1,3 МЛН