Python cv2 模块,minEnclosingCircle() 实例源码

我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用cv2.minEnclosingCircle()

项目:APEX    作者:ymollard    | 项目源码 | 文件源码
def find_center(self, name, frame, mask, min_radius):
        if name not in self.pts:
            self.pts[name] = deque(maxlen=self.params['tracking']['buffer_size'])

        # find contours in the mask and initialize the current (x, y) center of the ball
        cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

        # only proceed if at least one contour was found
        if len(cnts) > 0:
            # find the largest contour in the mask, then use it to compute the minimum enclosing circle and centroid
            c = max(cnts, key=cv2.contourArea)
            ((x, y), radius) = cv2.minEnclosingCircle(c)
            center = (int(x), int(y))

            # only proceed if the radius meets a minimum size
            if radius > min_radius:
                # draw the circle and centroid on the frame, then update the list of tracked points
                cv2.circle(frame, center, int(radius), (0, 255, 255), 2)
                cv2.circle(frame, center, 5, (0, 0, 255), -1)
                self.pts[name].appendleft(center)
                smooth_points = 8
                return (int(np.mean([self.pts[name][i][0] for i in range(min(smooth_points, len(self.pts[name])))])),
                        int(np.mean([self.pts[name][i][1] for i in range(min(smooth_points, len(self.pts[name])))]))), radius
        return None, None
项目:eclipse2017    作者:google    | 项目源码 | 文件源码
def getSunSize(self, p):
        """Get the size of the sun in screen pixels.

        This is a hack: it renders the sun, then finds the contour
        surrounding the sun and computes the center/radius of that.
        """
        self.fbo.bind()
        self.clear_background()
        self.fbo.release()
        dt, sun_alt, sun_az, moon_alt, moon_az, sun_r, moon_r, sep, parallactic_angle, lat, lon = p
        sun_coords = horizontal_to_cartesian(deg(sun_alt), deg(sun_az))
        sun_x, sun_y, sun_z = scale_vector(sun_coords, SUN_EARTH_DISTANCE)
        self.fbo.bind()
        self.draw_sun(sun_x, sun_y, sun_z)
        glFlush()
        self.fbo.release()
        image = self.fbo.toImage()
        # Find the contours of the sun in the image
        contours = self.find_contours(image)
        # Make a poly that fits the contour
        poly = cv2.approxPolyDP( np.array(contours[0]), 3, True )
        # Find the minimum enclosing circle of the polygon
        c = cv2.minEnclosingCircle(poly)
        self.fbo.bind()
        self.clear_background()
        self.fbo.release()
        return c
项目:cancer_nn    作者:tanmoyopenroot    | 项目源码 | 文件源码
def drawConvexHull(img, contours):
    cnt = contours[0]

    mask = np.zeros(img.shape, np.uint8)

    hull = cv2.convexHull(cnt,returnPoints = False)
    defects = cv2.convexityDefects(cnt,hull)

    for i in range(defects.shape[0]):
        s,e,f,d = defects[i,0]
        start = tuple(cnt[s][0])
        end = tuple(cnt[e][0])
        far = tuple(cnt[f][0])
        cv2.line(mask,start,end,[255,255,255],5)
        cv2.circle(mask,far,5,[255,255,255],-1)

    (x,y),radius = cv2.minEnclosingCircle(cnt)
    center = (int(x),int(y))
    radius = int(radius)
    cv2.circle(mask,center,radius,(255,255,255),-1)


    return mask
项目:cancer_nn    作者:tanmoyopenroot    | 项目源码 | 文件源码
def drawLines(img, contours):
    cnt = contours[0]
    (x,y),radius = cv2.minEnclosingCircle(cnt)
    center = (int(x),int(y))
    # radius = int(radius)
    # cv2.circle(mask,center,radius,(255,255,255),-1)

    mask = np.zeros(img.shape, np.uint8)
    cnt_points = []

    for cnt in contours:
        for pts in cnt:
            cnt_points.append(pts[0])

    cnt_points = np.array(cnt_points)
    # np.random.shuffle(cnt_points)
    # print cnt_points.shape
    # print cnt_points[0:10,:]

    for i in range(len(cnt_points)):
        cv2.line(mask,center,(cnt_points[i,0], cnt_points[i,1]),(255,255,255),5)

    return mask
项目:Glidr    作者:muinmomin    | 项目源码 | 文件源码
def augment_graph(frame, contour):
    if contour is None:
        return None, None
    moments = cv2.moments(contour)
    #Central mass of first order moments
    #if moments['m00']!=0:
    #    cx = int(moments['m10']/moments['m00']) # cx = M10/M00
    #    cy = int(moments['m01']/moments['m00']) # cy = M01/M00
    #centerMass = (cx,cy)
    #Draw center mass
    #circle
    (x,y),radius = cv2.minEnclosingCircle(contour)
    center = (int(x),int(y))
    radius = int(radius)
    cv2.circle(frame,center,7,[100,0,255],2)    
    cv2.circle(frame,center,radius,(92, 66, 244),5)
    return center, radius
项目:robot-camera-platform    作者:danionescu0    | 项目源码 | 文件源码
def find(self, image):
        hsv_frame = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(hsv_frame, self.__hsv_bounds[0], self.__hsv_bounds[1])
        mask = cv2.erode(mask, None, iterations=2)
        mask = cv2.dilate(mask, None, iterations=2)
        contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)[-2]
        if len(contours) == 0:
            return (False, False)
        largest_contour = max(contours, key=cv2.contourArea)
        ((x, y), radius) = cv2.minEnclosingCircle(largest_contour)
        M = cv2.moments(largest_contour)
        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

        return (center, radius)
项目:srcsim2017    作者:ZarjRobotics    | 项目源码 | 文件源码
def is_detector(self, img):
        """ This uses color to determine if we have a detector, and if so, returns where
            the big screen and smaller screen is in the subimage """
        lower = np.array([190, 190, 0], dtype = "uint8")
        upper = np.array([255, 255, 100], dtype = "uint8")
        mask = cv2.inRange(img, lower, upper)

        contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        contours = contours[0] if is_cv2() else contours[1]
        if len(contours) == 0:
            return None, False

        sorted_contours = sorted(contours, cmp=lambda a,b: int(cv2.contourArea(b)) - int(cv2.contourArea(a)))
        center, radius = cv2.minEnclosingCircle(sorted_contours[0])
        up = True
        if len(contours) > 1:
            center2, radius = cv2.minEnclosingCircle(sorted_contours[1])
            if center2[1] < center[1]:
                up = False

        if self.debug:
            debug_img = img.copy()
            cv2.drawContours(debug_img, [sorted_contours[0]], -1, (0, 255, 0), 2)
            cv2.imshow("cont", debug_img)
            cv2.waitKey(0)
            cv2.destroyAllWindows()

        return center, up
项目:srcsim2017    作者:ZarjRobotics    | 项目源码 | 文件源码
def is_repair_tool(self, img):
        """ This uses color to determine if we have a repair tool, and if so, returns where
            the button is located within the provided subimage """
        lower = np.array([190, 0, 0], dtype = "uint8")
        upper = np.array([255, 125, 100], dtype = "uint8")
        mask = cv2.inRange(img, lower, upper)

        contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        contours = contours[0] if is_cv2() else contours[1]
        if len(contours) == 0:
            return None, False

        sorted_contours = sorted(contours, cmp=lambda a,b: int(cv2.contourArea(b)) - int(cv2.contourArea(a)))
        center, radius = cv2.minEnclosingCircle(sorted_contours[0])
        up = True
        if center[1] > (img.shape[0] / 2):
            up = False

        if self.debug:
            debug_img = img.copy()
            cv2.drawContours(debug_img, [sorted_contours[0]], -1, (0, 255, 0), 2)
            cv2.imshow("cont", debug_img)
            cv2.waitKey(0)
            cv2.destroyAllWindows()

        return center, up
项目:keras-autoencoder    作者:Rentier    | 项目源码 | 文件源码
def detect_ball(frame):
    blurred = cv2.GaussianBlur(frame, (11, 11), 0)
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    mask = cv2.inRange(hsv, greenLower, greenUpper)
    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)

    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
    center = None

    # only proceed if at least one contour was found
    if len(cnts) == 0:
        return

    # find the largest contour in the mask, then use
    # it to compute the minimum enclosing circle and
    # centroid
    c = max(cnts, key=cv2.contourArea)
    ((x, y), radius) = cv2.minEnclosingCircle(c)
    M = cv2.moments(c)
    center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

    if radius < 10:
        print('Too small')
        return

    return center, radius
项目:shell_game    作者:BlakeStrebel    | 项目源码 | 文件源码
def callback(self,data):
        try:
            imgOriginal = self.bridge.imgmsg_to_cv2(data, "bgr8")
        except CvBridgeError as e:
            print("==[CAMERA MANAGER]==", e)

        blurred = cv2.GaussianBlur(imgOriginal,(11,11),0)
        hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)

        # lower = np.array([60,90,70])    # hsv range for green
        # upper = np.array([90,175,255])
        lower = np.array([60,70,70])    # hsv range for green
        upper = np.array([90,255,255])
        mask = cv2.inRange(hsv, lower, upper)
        mask = cv2.erode(mask, None, iterations=7)
        mask = cv2.dilate(mask, None, iterations=7)
        output = cv2.bitwise_and(imgOriginal, imgOriginal, mask = mask)
        outputGrayscale = cv2.cvtColor(output, cv2.COLOR_BGR2GRAY)

        if major_ver == '3':
            contours = cv2.findContours(outputGrayscale,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[1]
        elif major_ver == '2':
            contours = cv2.findContours(outputGrayscale,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[0]

        if len(contours) > 0:
            c = max(contours,key=cv2.contourArea)
            ((x,y),radius) = cv2.minEnclosingCircle(c)
            M = cv2.moments(c)
            treasureCenter = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
            self.treasurePoint.x = treasureCenter[0]
            self.treasurePoint.y = treasureCenter[1]
            self.treasurePoint.flag = 1
            self.pub.publish(self.treasurePoint)
        else:
            self.treasurePoint.flag = 0
            self.pub.publish(self.treasurePoint)

        cv2.imshow("TreasureFilter", output)
        cv2.waitKey(3)
项目:SharkCV    作者:hammerhead226    | 项目源码 | 文件源码
def __circle(self):
        (_, _), self._radius = cv2.minEnclosingCircle(self._ndarray)
项目:ROS-Robotics-By-Example    作者:PacktPublishing    | 项目源码 | 文件源码
def image_callback(self, msg):

      # convert ROS image to OpenCV image
      try:
         image = self.bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8')
      except CvBridgeError as e:
         print(e)

      # create hsv image of scene
      hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

      # find green objects in the image
      lower_green = numpy.array([50, 50, 177], numpy.uint8)      # fluffy green ball
      upper_green = numpy.array([84, 150, 255], numpy.uint8)
      mask = cv2.inRange(hsv, lower_green, upper_green)

      # dilate and erode with kernel size 11x11
      cv2.morphologyEx(mask, cv2.MORPH_CLOSE, numpy.ones((11,11))) 

      # find all of the contours in the mask image
      contours, heirarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
      self.contourLength  = len(contours)

      # Check for at least one ball found
      if self.contourLength < 1:
         print "No objects found"
         sys.exit("No objects found")        # if no Crazyflie in image, exit process

      ## Loop through all of the contours, and get their areas
      area = [0.0]*len(contours)
      for i in range(self.contourLength):
         area[i] = cv2.contourArea(contours[i])

      #### Ball #### the largest "green" object
      ball_image = contours[area.index(max(area))]

      # Find the circumcircle of the green ball and draw a blue outline around it
      (self.cf_u,self.cf_v),radius = cv2.minEnclosingCircle(ball_image)
      ball_center = (int(self.cf_u),int(self.cf_v))
      ball_radius = int(radius)
      cv2.circle(image, ball_center, ball_radius, (255,0,0), 2)

      # show image with green ball outlined with a blue circle
      cv2.imshow ("KinectV2", image)
      cv2.waitKey(3)


   # This callback function handles processing Kinect depth image, looking for the depth value 
   #   at the location of the center of the green ball on top of Crazyflie.
项目:ROS-Robotics-by-Example    作者:FairchildC    | 项目源码 | 文件源码
def image_callback(self, msg):

      # convert ROS image to OpenCV image
      try:
         image = self.bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8')
      except CvBridgeError as e:
         print(e)

      # create hsv image of scene
      hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

      # find green objects in the image
      lower_green = numpy.array([50, 50, 177], numpy.uint8)      # fluffy green ball
      upper_green = numpy.array([84, 150, 255], numpy.uint8)
      mask = cv2.inRange(hsv, lower_green, upper_green)

      # dilate and erode with kernel size 11x11
      cv2.morphologyEx(mask, cv2.MORPH_CLOSE, numpy.ones((11,11))) 

      # find all of the contours in the mask image
      contours, heirarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
      self.contourLength  = len(contours)

      # Check for at least one ball found
      if self.contourLength < 1:
         print "No objects found"
         sys.exit("No objects found")        # if no Crazyflie in image, exit process

      ## Loop through all of the contours, and get their areas
      area = [0.0]*len(contours)
      for i in range(self.contourLength):
         area[i] = cv2.contourArea(contours[i])

      #### Ball #### the largest "green" object
      ball_image = contours[area.index(max(area))]

      # Find the circumcircle of the green ball and draw a blue outline around it
      (self.cf_u,self.cf_v),radius = cv2.minEnclosingCircle(ball_image)
      ball_center = (int(self.cf_u),int(self.cf_v))
      ball_radius = int(radius)
      cv2.circle(image, ball_center, ball_radius, (255,0,0), 2)

      # show image with green ball outlined with a blue circle
      cv2.imshow ("KinectV2", image)
      cv2.waitKey(3)


   # This callback function handles processing Kinect depth image, looking for the depth value 
   #   at the location of the center of the green ball on top of Crazyflie.