Skip to content
Advertisement

morphological transformation opencv noob questiong

hope you all have good day today. so I’m here learning python,opencv on a raspberry pi and Im hoping that someone can explain what the code below do, I’ve read from https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html and it doesn’t explain what iterations mean and how to choose the best one? and what’s the use for object detection, thank you.

for frame in cam.capture_continuous(raw, format="bgr", use_video_port=True):
        frame = frame.array
        hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
        
        mask = cv2.inRange(hsv,colorLower,colorUpper)
        mask = cv2.blur(mask,(3,3))
        mask= cv2.dilate(mask,None,iterations=5)
        mask= cv2.erode(mask,None,iterations=1)
        mask= cv2.dilate(mask,None,iterations=3)
        
        me,thresh = cv2.threshold(mask,127,255,cv2.THRESH_BINARY)
    
        cnts = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2]
        center = None

Advertisement

Answer

It is quite an obvious concept, either way, as stated in the documentation:

iterations: number of times dilation is applied.

So iterations=5 means 5 consecutive times we’re applying dilation.

Regarding the applications for this procedure, I recommend you to read the Eroding and Dilating Tutorial from OpenCV which explains quite clearly how these methods work, but the absolute basics is that we need to erode and dilate to remove noise from the image and also close “holes” that wouldn’t make a solid contour.

The purpose of this transformations is to have a very solid image of the objects we’re looking for, to later detect contours.

The values for the number of iterations and transformations we apply vary greatly depending on the video, camera features, resolution, amount of noise, etc. You should experiment and find the optimal for your specific situation, or go for a generic erode + dilate and hope for best.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement