0

I am asked to count the number of objects in an image. We are allowed to use the cv2.dilate functions, as well as the cv2.thresholding images. The next step would be contouring the images so we can extract the number of objects in the image.

I got it to work using cv2.findContours, but I am asked to not use this function and instead implement it (or something with similar results) manually.

Current code and output below:

    # Read images
    
    img_5 = cv2.imread("image.jpg", 0)

    # filter on the images to account for the noise.
    
    img_5_blur = cv2.bilateralFilter(img_5, 50, 100, 100)
    
    # Next we are going to apply thresholding to the blurred images, like before
    
    threshold5, thresholded_image5 = cv2.threshold(img_5_blur, 127, 255, cv2.THRESH_BINARY)
    
    # Dilate the images to make the features stand out more, and make them easier to pick up using cv2.findContours. We can 
    # use the same kernel as before.
    
    dilated_image5 = cv2.dilate(thresholded_image5, threshold_kernel, iterations = 5)
    
    # We can proceed by using cv2.findContours (this is what needs to change!)
    
    contours_image5, hierarchy_information5 = cv2.findContours(dilated_image5, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

After this, I get the number of objects in the image by taking len(contours_image5):

    print("The number of objects found in the first image is ", len(contours_image5))
    >> 24

How do I do the contouring step without using built-in functions? Any help is appreciated, thank you!

Radogost
  • 143
  • 5
  • 16
Zendakeen
  • 33
  • 4

0 Answers0