Home
Login
Register
Search
Home
OpenCV Shape Detection - PyImageSearch
OpenCV Shape Detection - PyImageSearch
March 27, 2018 | Author: Anonymous rTTJELcsut | Category:
Shape
,
Computer Vision
,
C (Programming Language)
,
Parameter (Computer Programming)
,
Algorithms
DOWNLOAD
Share
Report this link
Comments
Description
6/21/2016 OpenCV shape detection PyImageSearch Navigation OpenCV shape detection by Adrian Rosebrock on February 8, 2016 in Image Processing, OpenCV 3, Tutorials Like 16 4 52 This tutorial is the second post in our three part series on shape detection and analysis. Last week we learned how to compute the center of a contour using OpenCV. Today, we are going to leverage contour properties to actually label and identify shapes in an image, just like in the figure at the top of this post. http://www.pyimagesearch.com/2016/02/08/opencvshapedetection/ 1/17 OpenCV shape detection Before we get started with this tutorial. c): 9 # initialize the shape name and approximate the contour 10 shape = "unidentified" 11 peri = cv2. 0.png Shell As you can see.pyimagesearch 2 | |--.py 3 | |--.__init__. make sure you have the imutils package installed on your system.6/21/2016 OpenCV shape detection PyImageSearch Looking for the source code to this post? Jump right to the downloads section. Open up the shapedetector.arcLength(c. We’ll skip the __init__ Python constructor here since 2/17 .pyimagesearch. let’s quickly review our project structure: OpenCV shape detection 1 |--.com/2016/02/08/opencvshapedetection/ class.py which will store our implementation of the ShapeDetector class.py 1 # import the necessary packages 2 import cv2 3 4 class ShapeDetector: 5 def __init__(self): 6 pass 7 8 def detect(self. we have defined a pyimagesearch module.py 5 |--.shapes_and_colors. a series of OpenCV convenience functions that we’ll be using later in this tutorial: OpenCV shape detection 1 $ pip install imutils Shell Defining our shape detector The first step in building our shape detector is to write some code to encapsulate the shape identification logic.04 * peri. True) 12 approx = cv2.approxPolyDP(c.shapedetector. we have the detect_shapes. Before we get started.py driver script that we’ll use to load an image from disk. ShapeDetector http://www. Finally.py file and insert the shapedetector. True) Line 4 starts the definition of our nothing needs to be initialized.detect_shapes. analyze it for shapes. Let’s go ahead and define our following code: ShapeDetector . and then perform shape detection and identification via the ShapeDetector class.py 4 |--. Inside this module we have shapedetector. In order to perform contour approximation.95 and ar <= 1. the shape is a rectangle 28 shape = "square" if ar >= 0. outline) of the shape we are trying to identify. As the name suggests.approxPolyDP method. it will have 5 vertices 31 elif len(approx) == 5: 32 shape = "pentagon" 33 34 # otherwise. contour approximation is an algorithm for reducing the number of points in a curve with a reduced set of points — thus the term approximation. w. cv2.pyimagesearch. otherwise.e. This algorithm is commonly known as the RamerDouglasPeucker algorithm. This leads to a resulting approximated curve that consists of a subset of points that were defined by the original cruve. or simply the splitand merge algorithm.approxPolyDP are normally in the range of 15% of the Note: Interested in a more indepth look at contour approximation? Be sure to check out the PyImageSearch Gurus course where I discuss computer vision and image processing fundamentals such as contours and connectedcomponent analysis in detail. it will have 3 vertices 15 if len(approx) == 3: 16 shape = "triangle" 17 18 # if the shape has 4 vertices.boundingRect(approx) 24 ar = w / float(h) 25 26 # a square will have an aspect ratio that is approximately 27 # equal to one. we can move on to performing shape detection: OpenCV shape detection 14 # if the shape is a triangle. Contour approximation is actually already implemented in OpenCV via the cv2. the contour (i.. Given our approximated contour. Contour approximation is predicated on the assumption that a curve can be approximated by a series of short line segments. we’ll be using contour approximation. we assume the shape is a circle 35 else: 36 shape = "circle" 37 http://www. y. Common values for the second parameter to original contour perimeter. In order to perform shape detection.05 else "rectangle" 29 30 # if the shape is a pentagon. we first compute the perimeter of the contour (Line 11). h) = cv2.com/2016/02/08/opencvshapedetection/ Python 3/17 . c . followed by constructing the actual contour approximation (Line 12).6/21/2016 OpenCV shape detection PyImageSearch We then have our detect method on Line 8 which requires only a single argument. it is either a square or 19 # a rectangle 20 elif len(approx) == 4: 21 # compute the bounding box of the contour and use the 22 # bounding box to compute the aspect ratio 23 (x. blur it slightly.com/2016/02/08/opencvshapedetection/ Python 4/17 . let’s create the detect_shapes. For example. "--image". we return the identified shape to the calling method. Finally. by process of elimination (in context of this example.py driver script: OpenCV shape detection 1 # import the necessary packages Free 21day crash course on computer 2 from pyimagesearch. Sound good? Enter which is the path to where the image we want to process resides on disk. then it must be either a square or a rectangle (Line 20). which is simply the width of the contour bounding box divided by the height (Lines 23 and 24). introduction to computer vision. 20 # and threshold it http://www.ArgumentParser() 9 ap. we can label it as a pentagon (Line 31 and 32). but don't know where to start? Let me implementation of the ShapeDetector class from the shapedetector submodule of pyimagesearch .0. then we are examining a square (since all sides have approximately equal length).shape[0]) 18 19 # convert the resized image to grayscale.shapedetector import ShapeDetector vision & image search engines 3 import argparse 4 import imutils 5 import cv2 6 7 # construct the argument parse and parse the arguments 8 ap = argparse.parse_args()) Free 21day crash course on computer vision & image search engines Python × Interested in computer vision and image search We start off on Lines 25 by importing our required packages. If a contour has five vertices. of course). We only need a single switch here. Email Address OpenCV shape detection 13 # load the image and resize it to a smaller factor so that 14 # the shapes can be approximated better LET'S DO IT! 15 image = cv2. let’s preprocess our image: a computer vision master. width=300) 17 ratio = image. I've created a free.add_argument("-i". then it must be a triangle (Lines 15 and 16). Otherwise. if the approximated contour has three vertices.pyimagesearch.imread(args["image"]) 16 resized = imutils. To determine which.shape[0] / float(resized. we compute the aspect ratio of the shape. 10 help="path to the input image") 11 args = vars(ap.resize(image. the shape is a rectangle. Otherwise. your email below to start your journey to becoming Next up. If the aspect ratio is ~1. 21day crash course that is handtailored to give you the best possible Lines 811 handle parsing our command line arguments. Shape detection with OpenCV Now that our ShapeDetector class has been defined. required=True. We can check the number of entries in this list to determine the shape of an object. If a contour has four vertices. we can make the assumption that the shape we are examining is a circle (Lines 35 and 36). --image . Notice how we’re importing our engines.6/21/2016 38 39 OpenCV shape detection PyImageSearch # return the name of the shape return shape It’s important to understand that a contour consists of a list of vertices. help. GaussianBlur(gray. 255. Email Address Lastly.com/2016/02/08/opencvshapedetection/ 5/17 .cvtColor(resized. cv2.6/21/2016 21 22 23 24 25 26 27 28 29 30 OpenCV shape detection PyImageSearch gray = cv2. The last step is to identify each of the contours: http://www.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils. and finally thresholding it to reveal the shapes in the image.RETR_EXTERNAL. (5. smoothing it to reduce high frequency noise. our image should look like this: Free 21day crash course on computer vision & image search engines Free 21day crash course on computer vision & image search engines × Interested in computer vision and image search engines. cv2.threshold(blurred.COLOR_BGR2GRAY) blurred = cv2. cv2. Notice how our image has been binarized — the shapes appear as a white foreground against a black background.THRESH_BINARY)[1] # find contours in the thresholded image and initialize the # shape detector cnts = cv2.is_cv2() else cnts[1] sd = ShapeDetector() First. Lines 2123 handle converting the resized image to grayscale.findContours(thresh. cv2. Sound good? Enter Figure 1: Thresholding reveals the shapes in our image. your email below to start your journey to becoming a computer vision master. we find contours in our binary image.pyimagesearch. handle grabbing the correct tuple value from LET'S DO IT! cv2. 21day crash course that is handtailored to give you the best possible introduction to computer vision. and finally initialize our ShapeDetector (Lines 2730).findContours based on our OpenCV version. From there. but don't know where to start? Let me help. we load our image from disk on Line 15 and resize it on Line 16. I've created a free. We then keep track of the ratio of the old height to the new resized height on Line 17 — we’ll find out exactly why we do this later in the tutorial.copy(). After thresholding. 5). 0) thresh = cv2. 60. waitKey(0) Python On Line 33 we start looping over each of the individual contours. 42 # then draw the contours and the name of the shape on the image 43 c = c.py --image shapes_and_colors. To see our shape detector in action. (255. 0). we draw the contours and the labeled shape on our image (Lines 4448).astype("int") 46 cv2. 48 0.imshow("Image".pyimagesearch. shape. Lastly.moments(c) 37 cX = int((M["m10"] / M["m00"]) * ratio) 38 cY = int((M["m01"] / M["m00"]) * ratio) 39 shape = sd. 255.6/21/2016 OpenCV shape detection PyImageSearch OpenCV shape detection 32 # loop over the contours 33 for c in cnts: 34 # compute the center of the contour.putText(image. [c]. then detect the name of the 35 # shape using only the contour 36 M = cv2. For each of them.png http://www. This will give us the correct (x. y)-coordinates by the resize ratio. cv2. 255. followed by performing shape detection and labeling. cY).5. 255). (0. we compute the center of the contour.astype("float") 44 c *= ratio 45 c = c. 2) 47 cv2. just execute the following command: OpenCV shape detection 1 $ python detect_shapes. image) 52 cv2.detect(c) 40 41 # multiply the contour (x. y)coordinates for both the contours and centroid of the original image.com/2016/02/08/opencvshapedetection/ Shell 6/17 . y)coordinates by our resize ratio (Lines 4345). Since we are processing the contours extracted from the resized image (rather than the original image).drawContours(image. (cX. we need to multiply the contours and center (x. followed by displaying our results (Lines 51 and 52).FONT_HERSHEY_SIMPLEX. -1. 2) 49 50 # show the output image 51 cv2. we were able to accurately label each of the shapes. This lesson is part of a three part series on shape detection and analysis. To accomplish this. we leveraged contour approximation.6/21/2016 OpenCV shape detection PyImageSearch Figure 2: Performing shape detection with OpenCV. Today we covered shape detection with OpenCV. our script loops over each of the shapes individually. Given the vertex count. performs shape detection on each one. based on this contour approximation.pyimagesearch. As you can see from the animation above. Then.com/2016/02/08/opencvshapedetection/ 7/17 . Summary In today’s post blog. we learned how to perform shape detection with OpenCV and Python. Last week we covered how to compute the center of a contour. we examined the number of vertices each shape has. Be sure to enter your email address in the form below to be notified when the next post goes live — you won’t want to miss it! http://www. And next week we’ll discuss how to label the actual color of a shape using color channel statistics. the process of reducing the number of points on a curve to a more simple approximated version. and then draws the name of the shape on the object. 6/21/2016 OpenCV shape detection PyImageSearch Downloads: If you would like to download the code and images used in this post. contour properties.com/2016/02/08/opencvshapedetection/ 8/17 . contours. Uncover exclusive techniques that I don't publish on this blog and start building image search engines of your own! Your email address DOWNLOAD THE GUIDE! approximate contours. shapes OpenCV center of contour Determining object color with OpenCV 27 Responses to OpenCV shape detection leena February 9. Enter your email address below to get my free 11page Image Search Engine Resource Guide PDF.zip of the code.pyimagesearch. I’ll also send you a FREE 11page Resource Guide on Computer Vision and Image Search Engines. enter your email address and I’ll send you the code immediately! Email address: Your email address DOWNLOAD THE CODE! Resource Guide (it’s totally free). including exclusive techniques that I don’t post on this blog! Sound good? If so. Not only will you get a . please enter your email address in the form below. find contours. 2016 at 5:59 am # REPLY Why it is scanning and labeling from bottom to top? How to to scan and label top to bottom? http://www. see this post. Thanks Vincent February 18.95 and ar <= 1.6/21/2016 OpenCV shape detection PyImageSearch Adrian Rosebrock February 9. It worked and I am able to scan from top to bottom. 2 boxes are connected with line/arrow with regards.0484 and shapefactor = 0. 2016 at 3:55 pm # REPLY Is there a particular reason you are taking the ratio of the area to the perimeter squared? It seems to make the rule more complicated. 2016 at 4:57 am # REPLY Thanks Adrian.06 and shapefactor = 0. 2016 at 11:11 pm # REPLY Actually I do not know the reason. Please help me in identifying lines connected with two shapes like in a flowchart. 2016 at 6:11 am # REPLY I have done the same with shape factor= area / (peri * peri) if shapefactor >= 0. just it got solved my problem.findContours method is implemented.05 else "rectangle" Adrian Rosebrock February 9. thank you for this excellent tutorial. leena February 17. First and foremost.050 and shapefactor = 0. Very useful and informative. 2016 at 3:41 pm # REPLY Hi Adrian.032 and shapefactor = 0. 2016 at 3:54 pm # REPLY That is how the cv2. leena February 10. http://www. You or somebody can help me understanding this and the better solution . If you would like to sort contours. so I took it.com/2016/02/08/opencvshapedetection/ 9/17 .pyimagesearch. leena February 9. For more advanced shapes. the moment(cnt) will not get a correct value. Play around with the percentage used in cv2.pyimagesearch.jpg file as the source. A little feedback on the image file.com/6Z9CnBA I’ve noticed that sometimes a very messy contour will be classified incorrectly as a triangle. 2016 at 7:49 pm # REPLY Hi Adrian. Peng March 4. I have also tweaked the shapedetector class to identify only triangles. I am able to successfully identify a red triangle. The code detailed in this post assumes simple shapes that can be recognized utilizing contour properties.com/4a06psM What would be a good way to tweak this? http://pastie.org/10727912 http://pastie.approxPolyDP and you’ll be able to see the differences. http://imgur. Anyway. you might need to train your own custom object detector.org/10727915 Adrian Rosebrock February 18. the reason sometimes even messy contours get classified differently is due to the contour approximation. or shapes that have substantial variances in how they appear (such as noisy contours).com/2016/02/08/opencvshapedetection/ 10/17 . Thank you for making this. It report an error : cntX = int(M[“m10”] / M[“m00”]) ZeroDivisionError: float division by zero Any ideas on this? Thanks Adrian Rosebrock March 6. you can resolve the issue by doing: 1 if M["m00"] > 0: http://www. http://imgur. 2016 at 9:20 am # REPLY Version version of OpenCV and Python are you using? In either case.6/21/2016 OpenCV shape detection PyImageSearch I have used the logic here to detect red triangles in a webcam feed. I notice that if using a . 2016 at 4:05 pm # REPLY Keep in mind that the code is only as good as the images that you put into it. Alternatively. I’m a mechanical engineer and noob to openCV. I believe this is probably due to an update of how python works from how it worked when you wrote this tutorial. Which version of OpenCV and NumPy are you using? brandon March 11. 2016 at 4:20 pm # REPLY Adrian.. line 46.0 and python2. 2016 at 12:28 pm # http://www. 2016 at 10:21 am # REPLY I personally haven’t seen this error message before. in 2 c *= ratio 3 TypeError: Cannot cast ufunc multiply output from dtype('float64') to dtype('int32') with Adrian Rosebrock March 13.pyimagesearch. and plan on purchasing the book soon. I was working through this post for now. Is this the case? Adrian Rosebrock March 13. python and linux and have managed to get openCV 3.com/2016/02/08/opencvshapedetection/ REPLY 11/17 . 2016 at 10:29 am # REPLY Interesting. Brandon mentioned this issue in a comment above. continue to process the contour This if statement will take care of the divide by zero error. I needed to modify “float” on line 17 to “int” as it was causing cast problems on line 43 “c *=ratio”. 2016 at 10:00 pm # REPLY Hi Adrian.com/2015/06/22/installopencv30andpython27onubuntu/ In order to get this code running on my setup. Firstly thanks for a great tutorial and site.py".6/21/2016 OpenCV shape detection PyImageSearch 2 # . you can add a tiny value to the moment to ensure there is no divide by zero problem: cX = (M["c10"] / (M["m00"] + 1e‐7)) Euan March 10. Can you let me know which OpenCV and NumPy versions you are using? Brandon March 14..pyimagesearch.7 setup thanks to your tutorial here…. great stuff. I’ve learned a lot from your blog. http://www. and I’m getting the following traceback error: 1 File "detect_shapes. 2016 at 9:14 am # http://www. and it happens with both OpenCV 2.3 The workaround was simply to adjust data types pre and post multiplication: c=c. I’m using NumPy 1. you just need to apply contour approximation first. Ahmed Abdeldaim March 26. 2016 at 3:15 pm # REPLY Thanks for the tip Brandon! I’ll be sure to dive into this more. darshan March 26.6/21/2016 OpenCV shape detection PyImageSearch numpy is 1.pyimagesearch.astype(np.float_) c *= ratio c=c.int32) It works now. 2016 at 2:09 am # REPLY how to install imutils module I used pip install imutils I’m getting error Adrian Rosebrock March 27.4.com/2016/02/08/opencvshapedetection/ REPLY 12/17 .1.0 (in a virtualenv.10.4.9.12 and 3.astype(np.11.3. thanks to another of your tutorials) under Python 2. so perhaps this is an issue with NumPy 1.10. 2016 at 4:05 pm # REPLY Thanks for your help. but I would start with this one. I detail contour approximation in a few blog posts.X. for example by reduce point size ?? or this is the best result?? Adrian Rosebrock March 24. 2016 at 5:10 pm # REPLY Absolutely. Ahmed Abdeldaim March 24.7 on OS X 10. 2016 at 10:30 am # REPLY Great work Mr. Adrian Rosebrock March 14. Adrian but is there a way to make the selection more softer. approxPolyDP parameters. Diego Fernando Barrios April 29. I’m working in my work grade. you´re doing a great and util work. 2016 at 5:08 pm # REPLY Good afthernoon! Thanks very much for this tutotrial. http://www. itai May 8. I have a problem with contour detection. 2016 at 3:55 pm # REPLY Depending on your image.com/2016/02/08/opencvshapedetection/ 13/17 . You might need to tweak the cv2. when I change the image.6/21/2016 OpenCV shape detection PyImageSearch Please see the “OpenCV shape detection” section of this blog post. this could be an issue with segmentation and/or the contours. From there. 2016 at 2:09 pm # REPLY Make sure you click on the window and press any key on your keyboard — this will advance the script. the project don’t work (I’m using a black background. The python scripts should recognize (9 “nine” rectangles”) but just one is recognized Sorry for the writing. I would like that you can help me.pyimagesearch. my english is not so good. Make sure that after thresholding your 9 rectangles have been clearly segmented. You just need to use pip $ pip install imutils firoz khan April 23. Thanks very much! Adrian Rosebrock April 30. Friend. Right now a keypress is required after each detection. 2016 at 4:24 am # REPLY Hey Adrian. move on to the contour approximation and see how many points are returned by the approximation. 2016 at 10:42 am # REPLY hi adrian it is only detcting one pentagon and nothing else Adrian Rosebrock April 25. I not have problem with the image path. I take the image from USB camera). In this case. 2016 at 8:12 am # REPLY The contour approximation algorithm and Convex Hull algorithm are used for two separate purposes.com/2016/02/08/opencvshapedetection/ 14/17 . As the name implies. instead of using the convex hull ? Thanks Adrian Rosebrock May 8. while ensuring that all points in the resulting approximation were also part of the original shape. not a simplification of the contour shape and the resulting convex hull actually contains points that are not part of the original shape. Leave a Reply Name (required) Email (will not be published) (required) Website SUBMIT COMMENT Resource Guide (it’s totally free). Your resulting contour approximation is this a simplification of the shape by utilizing points that are already part of the shape. Click the button below to get my free 11page Image Search Engine Resource Guide PDF. Uncover exclusive http://www. by definition. y) coordinates that comprise the contour.pyimagesearch. contour approximation is used to reduce the number of points along a contour by “simplifying” the contour based on a percentage of the perimeter. I used contour approximation because I wanted to reduce the number of (x. The convex hull on the other hand is the smallest convex set that contains all points along the contour — it is.6/21/2016 OpenCV shape detection PyImageSearch I was wondering why did you use the RamerDouglasPeucker algorithm to reduce the set of points. CLICK HERE TO MASTER FACE DETECTION PyImageSearch Gurus: NOW ENROLLING! The PyImageSearch Gurus course is now enrolling! Inside the course you'll learn how to perform: http://www. Click here to give it a shot yourself.6/21/2016 OpenCV shape detection PyImageSearch techniques that I don't publish on this blog and start building image search engines of your own.com/2016/02/08/opencvshapedetection/ 15/17 . Download for Free! You can detect faces in images & video. Are you interested in detecting faces in images & video? But tired of Googling for tutorials that never work? Then let me help! I guarantee that my new book will turn you into a face detection ninja by the end of this weekend.pyimagesearch. tips. tricks.D who has launched two successful image search engines. I know.com/2016/02/08/opencvshapedetection/ 16/17 . It sounds crazy. CLICK HERE TO BECOME AN OPENCV NINJA Subscribe via RSS Never miss a post! Subscribe to the PyImageSearch RSS Feed and keep up to date with my image search engine tutorials. Learn computer vision in a single weekend. and tricks http://www. Want to learn computer vision & OpenCV? I can teach you in a single weekend. quickstart guide to becoming an OpenCV Ninja. ID My Pill and Chic Engine. I'm here to share my tips.pyimagesearch. and hacks I've learned along the way. So why not give it a try? Click here to become a computer vision ninja. take a tour. My new book is your guaranteed.6/21/2016 OpenCV shape detection PyImageSearch Automatic License Plate Recognition (ANPR) Deep Learning Face Recognition and much more! Click the button below to learn more about the course. TAKE A TOUR & GET 10 (FREE) LESSONS Hello! I’m Adrian Rosebrock. I'm an entrepreneur and Ph. and get 10 (FREE) sample lessons. but it’s no joke. 0 for both Python 2. 2015 How to install OpenCV 3 on Raspbian Jessie OCTOBER 26. 2015 Search Search.7 and Python 3+ on your Raspberry Pi 2 JULY 27. 2015 Basic motion detection and tracking with Python and OpenCV MAY 25. 2015 Home surveillance and motion detection with the Raspberry Pi.pyimagesearch. © 2016 PyImageSearch.0 and Python 2.7+ on Ubuntu JUNE 22.6/21/2016 OpenCV shape detection PyImageSearch POPULAR Install OpenCV and Python on your Raspberry Pi 2 and B+ FEBRUARY 23. Google+. Facebook. 2015 Installing OpenCV 3.7+ on OSX JUNE 15. OpenCV. All Rights Reserved. and LinkedIn.. and Dropbox JUNE 1. Python. 2015 Install OpenCV 3. http://www..0 and Python 2.com/2016/02/08/opencvshapedetection/ 17/17 . Find me on Twitter. 2015 Install OpenCV 3.
Report "OpenCV Shape Detection - PyImageSearch"
×
Please fill this form, we will try to respond as soon as possible.
Your name
Email
Reason
-Select Reason-
Pornographic
Defamatory
Illegal/Unlawful
Spam
Other Terms Of Service Violation
File a copyright complaint
Description
Copyright © 2024 DOKUMEN.SITE Inc.