IE-482-582 / fall2019

Course materials for the Fall 2019 semester of IE 482/582
8 stars 6 forks source link

Contours for ball tracking imporved for better tracking. #18

Open dave816 opened 4 years ago

dave816 commented 4 years ago
  1. I converted rgb image to hsv first and then applied gaussian blur.
  2. The earlier code used RETR_EXTERNAL for contour mapping which retrieved external contour. I used RETR_TREE that calculates the full hierarchy of the contours since the ball has different shades. Since RETR TREE spews out two values contours and its hierarchy but we only need contours so cntrs,_ has been added.
  3. CHANGE MADE has been added in the code lines to show changes

if (self.trackMethod == 'contours'):
            # OPTION 1 -- USE CONTOURS.
            # See https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/

            # resize the frame, blur it, and convert it to the HSV
            # color space.
            # frame = imutils.resize(frame, width=600)
                        # CHANGE MADE
            blurred = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
            hsv = cv2.GaussianBlur(blurred, (11, 11), 0)

            # construct a mask for the color "red", then perform
            # a series of dilations and erosions to remove any small
            # blobs left in the mask
            red_mask = cv2.inRange(hsv, self.lower_red, self.upper_red)
            red_mask[0:search_top, 0:w] = 0
            red_mask[search_bot:h, 0:w] = 0     
            red_mask = cv2.erode(red_mask, None, iterations=2)
            red_mask = cv2.dilate(red_mask, None, iterations=2)         

            # find contours in the mask and initialize the current
            # (x, y) center of the ball
                        # CHANGE MADE
            cntrs,_ = cv2.findContours(red_mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

            # cntrs = cntrs[0] if imutils.is_cv2() else cntrs[1]

            # only proceed if at least one contour was found
            if len(cntrs) > 0:
                # find the largest contour in the mask, then use
                # it to compute the minimum enclosing circle and
                # centroid
                c = max(cntrs, key=cv2.contourArea)
                ((cx, cy), r) = cv2.minEnclosingCircle(c)
                M = cv2.moments(c)
                center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

                # only proceed if the radius meets a minimum size
                if r > 10:
                    # draw the circle and centroid on the frame
                    cv2.circle(image, (int(cx), int(cy)), int(r),
                        (0, 255, 255), 2)
                    cv2.circle(image, center, 5, (0, 0, 255), -1)

                    radius = int(r)
                    x = int(cx)
                    y = int(cy)

            # Move the robot.
            # NOTE:  This method uses the RADIUS of the circle.
            self.moveMe(x, w, self.goal_radius, radius)