OpenCV Contours Detection and Visualization: A Python Example
This Python code snippet utilizes the OpenCV library to perform contour detection and visualization within an image. It begins by reading an image ('practice.png') using 'cv2.imread', converting it to grayscale. The function 'cv2.findContours' is employed to identify contours in the image using the specified algorithm ('cv2.RETR_TREE' for hierarchical representation and 'cv2.CHAIN_APPROX_SIMPLE' for simple contour approximation). The output 'contours' stores the identified contours, while 'hierarchy' provides information about the parent-child relationships between them. The code proceeds to draw these contours on the image using 'cv2.drawContours', iterating through each contour (indexed from 0). Each iteration highlights a specific contour with a distinct color (128 for the first contour, 200 for the remaining) and a thickness of -1 (filling the contour). The 'cv2.imshow' function displays the modified image with the drawn contours, using the contour index as the window title. Finally, 'cv2.waitKey()' ensures that the window remains open until a key press, allowing the user to observe the results. This code demonstrates a fundamental example of contour detection and visualization within an image using OpenCV, providing a basis for further exploration and image analysis tasks.
原文地址: https://www.cveoy.top/t/topic/mUwG 著作权归作者所有。请勿转载和采集!