OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and also we are going to use cv2.drawContours() function to draw edges on images. A contour is an outline or a boundary of shape.
- Import module
- Import image
- Convert it to grayscale image
- Apply thresholding on image and then find out contours.
- Run a loop in the range of contours and iterate through it.
- In this loop draw a outline of shapes (Using drawContours() ) and find out center point of shape.
- Classify the detected shape on the basis of a number of contour points it has and put the detected shape name at the center point of shape.
- cv2.findContours(): Basically this method find outs all the boundary points of shape in image.
Syntax: cv2.findContours(src, contour_retrieval, contours_approximation)
- src: input image n-dimensional (but for in our example we are going to use 2 dimensional image which is
- cv.RETR_EXTERNAL:retrieves only the extreme outer contours
- cv.RETR_LIST:retrieves all of the contours without establishing any hierarchical relationships.
- cv.RETR_TREE:retrieves all of the contours and reconstructs a full hierarchy of nested contours.
- cv.CHAIN_APPROX_NONE: It will store all the boundary points.
- cv.CHAIN_APPROX_SIMPLE: It will store number of end points(eg.In case of rectangle it will store 4)
Return value: list of contour points
- cv2.drawContours() : This method draws a contour. It can also draw a shape if you provide boundary points.
Syntax: cv.DrawContours(src, contour, contourIndex, colour, thickness)
- src: n dimensional image
- contour: contour points it can be list.
- -1:draw all the contours
- To draw individual contour we can pass here index value
- color:color values
- thickness: size of outline
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.