How to Detect Shapes with OpenCV [Python]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody welcome back to another video in today's tutorial video we'll be detecting shapes in opencv using the python coding language we'll be detecting shapes and images all the code will be on github and all the links will be in the description before we start though please be sure to like the video and subscribe to the channel let's get into the video alright so i'm in visual studio code here with the python project setup already and i'll be assuming you already have python as well as opencv setup and just for reference this will be the image that i'll use to detect shapes on the first thing we need to do is to import opencv and then we need to load in the image that we want to detect shapes on so inside of this imread function we need to pass a string containing the path to our image file so i'll just paste mine here and to make sure there aren't any problems with our code make sure to add an extra backslash at each existing one after this we need to convert our image to a grayscale image and we need to do this by using the cvt color function and in here we pass our image and then the conversion we want which is cv2.color bgr2gray in our case we then need to create a threshold image and i'll first type out everything and explain afterwards so inside of this threshold function we pass our grayscale image then the threshold number then the gray color we want to make the pixels that don't meet the threshold requirement and then cv2.thresh binary this function returns two values where this first one is the type of threshold that was used but since it's of no use to us i've made mine in underscore the second value then stores the threshold image which is what we're actually interested in now this threshold function basically takes our gray image then it takes the value we gave in our second parameter and for each pixel in our image if the pixel's gray value is equal to or below this number the function will make the pixel black and then for each other pixel the program will make it the value we put in here which is white the last parameter is the type of thresholding that we want and i'll leave a link to all the types if you want to go into more detail we should then end up with an image that looks something like this where the image consists of two colors and just a quick note if you're not working with light or bright colors such as yellow then you can set this value here a bit lower maybe something like 150 or even lower now that we have that out of the way we can start finding the edges of the shapes in our new threshold image which was why we needed this threshold image in the first place so that we can detect the edges of the shapes accurately without any other colors interfering to detect these edges we need to create two variables because this function returns two values this first one is a list of all the contours which are basically our outlines and the second one stores the relationship that each of the contours have with each other in our find contours function we need to pass our threshold image then one of these four contour retrieval modes so i'll choose retrieve tree and then in our third parameter we need one of these two values and so i'll choose chain approx simple since it saves much more memory than chain approx none this screenshot explains very well what these two approximation methods do and as we can see this simple one only stores necessary points while the other one stores multiple points that aren't important to us if you want more detail about anything relating to contours in opencv then i'll leave a link in the description to open cv's documentation covering the subject the next step is to iterate through each contour but we also want to get the iteration number so we'll use the enumerate function where this i loop variable will store the current iteration number and contour will store the current contour that we're iterating through so the reason we want to do this is because of the following two lines of code if i is equal to zero then continue basically our shape detection program will detect the entire image itself as a shape but since we don't want that we choose to ignore the first contour because it is the first one that stores the whole image as a shape we then need to write two more lines of code but i'll type it out first and explain afterwards so in this epsilon variable i'll store 0.01 times cv2 dot arc length where i'll pause contour as well as true in the second line we'll create a variable called the prox and store cv2 dot approx poly dp where we'll store contour epsilon and true this is probably the most difficult part of this shape detection program but basically what these two lines of code do is approximate the shape we want and what that means is that when we have a shape like this one where there are some imperfections then the bot will ignore those imperfections and still count this as a rectangle or a quadrilateral in our case this first variable is our epsilon which we use to specify the precision that the approximation function will use to approximate the shape but in almost every single case you should be fine with 0.01 this true variable that we pause here just tells the bot that the contour is a closed shape we then get to this second line which will approximate our shape using the current contour in the for loop using this precision and then once again here we tell the program that the contour is a closed shape you can then draw the contours on the screen using the draw contours function passing image contour and then as our third argument we pass the contour id but since we already have a reference to the specific contour we should pause zero we then pass the color we want the outline to be in bgr format so for example if you want black you should pause two five five at each one or if you want red then you only make this last one two five five and then in our last parameter we need to pause the thickness of the contour which i'll make for we then need to find out the coordinates of the contour that we want to put the text on and so i'll create x y width and height variables and type cv2 bounding rect and pass approx this function returns these four values we can then find the center of the contour by finding the middle x and y coordinates and to do this we can create an x mid variable where we'll say x plus half of width and this will give us the middle similarly we can do this with the y coordinate but only we plus half of height make sure to convert each of these to integers otherwise your program might try to find half pixels i do need to mention that yes we do now have the center of the shape but if we place text at these coordinates then we'll end up with this result because the top left coordinates of the text will be placed at these center coordinates and so our text is not in the middle we can put our text in the exact middle though if we find the length and height of the text in pixels divided by 2 and then minus it from each of these results but since the position of the text doesn't matter too much and we only want to know what shape it is i'll guess the middle of each contour and so i found that dividing width with about 3 should work well enough and height with about 1.5 should also work well enough after this we need to create some variables that we'll use to display the text on the screen so we can create a coordinates variable to make it more convenient and store a tuple of x mid and y mid we'll also need a color variable which will be the color of the text but since i want it black i'll make mine 0 at each and then finally we need a variable to store the font of the text so i'll be choosing the hershey duplex font now we get to the part where we actually recognize the shapes based on the amount of corners they have and so we look at the length of our approximated shapes and if the length is 3 then the shape has three corners which means that the shape is a triangle and underneath here we type cv2.put text to put the text on the screen we then pass our original image the shape we think we've detected the coordinates the font the font scale which will pass as one the color and then the thickness which i'll also pass as one now we need to copy and paste this text a few times and only change the numbers here at the top as well as the text if you want you can add shapes with more than six corners by copy and pasting this however much you'd like but i'd like to only find shapes all the way up to six corners for the sake of simplicity then we need to change all of these if statements except for the first one to else if statements because we need to add a lost else statement at the end here where we'll only copy and paste the text part of the code and change this text to circle then we can finally exit the for loop and show the image on the screen when we run our program and so we type in show then we pause the window name as a string and then the image we want to show we'll also need to add this weight key function and pass in zero so that our image only shows until we end the program now if we run this program we should end up with the final image and as we can see each of the shapes has text on it where it tells us the name of the shape and it seems quite accurate but with all that said that's the end of the video please remember to like the video and subscribe to the channel and i hope to see you in the next one
Info
Channel: CreepyD
Views: 22,152
Rating: undefined out of 5
Keywords: how to detect shapes in opencv, how to detect shapes in python, how to identify shapes in python, shape detection opencv, shape detection python, shape detection github, shape detection api, shape detection algorithm, shape detection in python, shape detection using opencv, shape detection in opencv, shape detection opencv github, shapes in python, shapes in python code, python shape detection, shape detection python code, opencv shape detection python, opencv shape detection
Id: Wl11eloYVm8
Channel Id: undefined
Length: 7min 52sec (472 seconds)
Published: Sat Jan 29 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.