{"id":17492,"date":"2021-06-07T17:41:46","date_gmt":"2021-06-07T17:41:46","guid":{"rendered":"https:\/\/www.askpython.com\/?p=17492"},"modified":"2021-06-07T17:41:47","modified_gmt":"2021-06-07T17:41:47","slug":"python-detecting-contours","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/python-detecting-contours","title":{"rendered":"Python: Detecting Contours"},"content":{"rendered":"\n<p>Hello fellow learner! Today we will learn about detecting contours in an image. Contours are defined as refined boundaries of objects and can be really helpful in detecting objects.<\/p>\n\n\n\n<p><strong><em>Recommended read: <a href=\"https:\/\/www.askpython.com\/python\/examples\/edge-detection-in-images\" data-type=\"post\" data-id=\"17372\">How to detect edges in Python?<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Detecting Contours using Python<\/h2>\n\n\n\n<p>So let&#8217;s get started with Detecting Contours for images using the OpenCV library in Python.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Importing Modules<\/h3>\n\n\n\n<p>First, we import the necessary modules which include <a href=\"https:\/\/www.askpython.com\/python-modules\/read-images-in-python-opencv\" data-type=\"post\" data-id=\"8838\">OpenCV<\/a> and <a href=\"https:\/\/www.askpython.com\/python-modules\/matplotlib\/python-matplotlib\" data-type=\"post\" data-id=\"3182\">matplotlib<\/a> to plot the images on the screen.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nimport cv2\nimport matplotlib.pyplot as plt\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">2. Loading the image into the program<\/h3>\n\n\n\n<p>The next step includes loading the image from the file directory to our program using the <code>imread<\/code> function and then converting the image into <code>RGB<\/code> format.<\/p>\n\n\n\n<p>We will plot the images in form of a <code>subplot<\/code> where the first image is the original loaded image. The code for the same is shown below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nloaded_img = cv2.imread(&quot;image.jpg&quot;)\nloaded_img = cv2.cvtColor(loaded_img, cv2.COLOR_BGR2RGB)\n\nplt.figure(figsize=(20,20))\n\nplt.subplot(2,2,1)\nplt.title(&quot;Original Image&quot;)\nplt.imshow(loaded_img)\nplt.axis(&quot;off&quot;)\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">3. Converting image to GrayScale<\/h3>\n\n\n\n<p>For better detection of contours, we convert the image to a grayscale image by using <code>cvtColor<\/code> function. After converting the image to grayscale we plot it on the second subplot on the main plot.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\ngray_image = cv2.cvtColor(loaded_img, cv2.COLOR_RGB2GRAY)\nplt.subplot(2,2,2)\nplt.title(&quot;Grayscale Image&quot;)\nplt.imshow(gray_image,cmap=&quot;gray&quot;)\nplt.axis(&quot;off&quot;)\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">4. Getting Binary Image<\/h3>\n\n\n\n<p>Next we convert the image into a binary image as it makes the image processing much much easier as it removes the unnecessary items from the image and focuses on the important objects only.<\/p>\n\n\n\n<p>The code for the same is shown below. We will be plotting the binary image on the third slot on the main plot.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\n_, binary_img = cv2.threshold(gray_image, 225, 255, cv2.THRESH_BINARY_INV)\nplt.subplot(2,2,3)\nplt.title(&quot;Binary Image&quot;)\nplt.imshow(binary_img,cmap=&quot;gray&quot;)\nplt.axis(&quot;off&quot;)\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">5. Detecting Contours<\/h3>\n\n\n\n<p>The final step is to detect contours using the <code>findContours<\/code> method of openCV library and then we draw the contours on the image.<\/p>\n\n\n\n<p>We then plot all the images in the subplot, the code for the same is shown below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\ncontours, hierarchy = cv2.findContours(binary_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\nfinal_image = cv2.drawContours(loaded_img, contours, -1, (0, 255, 0), 2)\nplt.subplot(2,2,4)\nplt.title(&quot;Contours detected Image&quot;)\nplt.imshow(final_image,cmap=&quot;gray&quot;)\nplt.axis(&quot;off&quot;)\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">The Output Plot<\/h2>\n\n\n\n<p>The final output of the whole procedure explained above is shown below. You can see that the results are very accurate.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"518\" height=\"368\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/05\/Contour_Detection_output_1.jpg\" alt=\" Contour Detection Output 1 Detecting Contours\" class=\"wp-image-17498\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/05\/Contour_Detection_output_1.jpg 518w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/05\/Contour_Detection_output_1-300x213.jpg 300w\" sizes=\"auto, (max-width: 518px) 100vw, 518px\" \/><figcaption>Contour Detection Output 1<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">The Final Code for Detecting Contours<\/h2>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nimport cv2\nimport matplotlib.pyplot as plt\n\nloaded_img = cv2.imread(&quot;image1.png&quot;)\nloaded_img = cv2.cvtColor(loaded_img, cv2.COLOR_BGR2RGB)\n\nplt.figure(figsize=(20,20))\n\nplt.subplot(2,2,1)\nplt.title(&quot;Original Image&quot;)\nplt.imshow(loaded_img)\nplt.axis(&quot;off&quot;)\n\ngray_image = cv2.cvtColor(loaded_img, cv2.COLOR_RGB2GRAY)\nplt.subplot(2,2,2)\nplt.title(&quot;Grayscale Image&quot;)\nplt.imshow(gray_image,cmap=&quot;gray&quot;)\nplt.axis(&quot;off&quot;)\n\n_, binary_img = cv2.threshold(gray_image, 225, 255, cv2.THRESH_BINARY_INV)\nplt.subplot(2,2,3)\nplt.title(&quot;Binary Image&quot;)\nplt.imshow(binary_img,cmap=&quot;gray&quot;)\nplt.axis(&quot;off&quot;)\n\ncontours, hierarchy = cv2.findContours(binary_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\nfinal_image = cv2.drawContours(loaded_img, contours, -1, (0, 255, 0), 2)\nplt.subplot(2,2,4)\nplt.title(&quot;Contours detected Image&quot;)\nplt.imshow(final_image,cmap=&quot;gray&quot;)\nplt.axis(&quot;off&quot;)\n\nplt.savefig(&#039;Contour_Detection_output_2.png&#039;, dpi = 1000,bbox_inches = &#039;tight&#039;)\nplt.tight_layout()\nplt.show()\n<\/pre><\/div>\n\n\n<p>I also tried the same code for a different image. The results are displayed below.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"519\" height=\"445\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/05\/Contour_Detection_output_2.jpg\" alt=\"Contour Detection Output 2 Detecting Contours\" class=\"wp-image-17500\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/05\/Contour_Detection_output_2.jpg 519w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/05\/Contour_Detection_output_2-300x257.jpg 300w\" sizes=\"auto, (max-width: 519px) 100vw, 519px\" \/><figcaption>Contour Detection Output 2<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Congratulations! Now you are one step closer to detecting objects from images. We learned to detect the proper boundaries of the objects today!<\/p>\n\n\n\n<p>Keep learning! Happy coding!<\/p>\n\n\n\n<p>Thank you for reading!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello fellow learner! Today we will learn about detecting contours in an image. Contours are defined as refined boundaries of objects and can be really helpful in detecting objects. Recommended read: How to detect edges in Python? Detecting Contours using Python So let&#8217;s get started with Detecting Contours for images using the OpenCV library in [&hellip;]<\/p>\n","protected":false},"author":28,"featured_media":17493,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-17492","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/17492","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/28"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=17492"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/17492\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/17493"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=17492"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=17492"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=17492"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}