python类moments()的实例源码

follower.py 文件源码 项目:andruinoR2 作者: andruino 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def image_callback(self, msg):
    image = self.bridge.imgmsg_to_cv2(msg,desired_encoding='bgr8')
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    lower_yellow = numpy.array([18,  120,  200])
    upper_yellow = numpy.array([28, 255, 255])
    mask = cv2.inRange(hsv, lower_yellow, upper_yellow)

    h, w, d = image.shape
    search_top = 3*h/4
    search_bot = 3*h/4 + 20
    mask[0:search_top, 0:w] = 0
    mask[search_bot:h, 0:w] = 0
    M = cv2.moments(mask)
    if M['m00'] > 0:
      cx = int(M['m10']/M['m00'])
      cy = int(M['m01']/M['m00'])
      cv2.circle(image, (cx, cy), 20, (0,0,255), -1)
      # BEGIN CONTROL
      err = cx - w/2
      self.twist.linear.x = 0.2
      self.twist.angular.z = -float(err) / 100
      self.cmd_vel_pub.publish(self.twist)
      # END CONTROL
    cv2.imshow("window", image)
    cv2.waitKey(3)
__init__.py 文件源码 项目:rubiks-cube-tracker 作者: dwalton76 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, rubiks_parent, index, contour, heirarchy):
        self.rubiks_parent = rubiks_parent
        self.index = index
        self.contour = contour
        self.heirarchy = heirarchy
        peri = cv2.arcLength(contour, True)
        self.approx = cv2.approxPolyDP(contour, 0.1 * peri, True)
        self.area = cv2.contourArea(contour)
        self.corners = len(self.approx)
        self.width = None

        # compute the center of the contour
        M = cv2.moments(contour)

        if M["m00"]:
            self.cX = int(M["m10"] / M["m00"])
            self.cY = int(M["m01"] / M["m00"])
        else:
            self.cX = None
            self.cY = None
main_function.py 文件源码 项目:edison_developing 作者: vincentchung 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def camera_gesture_trigger():
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray,(5,5),0)
    ret,thresh1 = cv2.threshold(blur,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

    contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    max_area=0

    for i in range(len(contours)):
        cnt=contours[i]
        area = cv2.contourArea(cnt)
        if(area>max_area):
            max_area=area
            ci=i
    cnt=contours[ci]
    hull = cv2.convexHull(cnt)
    moments = cv2.moments(cnt)

    cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    hull = cv2.convexHull(cnt,returnPoints = False)

    defects = cv2.convexityDefects(cnt,hull)                    

    if defects is not None:         
        if defects.shape[0] >= 5:
            return 1

    return 0
cv.py 文件源码 项目:Pacbot 作者: HarvardURC 项目源码 文件源码 阅读 55 收藏 0 点赞 0 评论 0
def _detect_bot(self, hsv_image):
        BOT_MIN = np.array([28,8,100], np.uint8)
        BOT_MAX = np.array([32,255,255], np.uint8)

        thresholded_image = cv2.inRange(hsv_image, BOT_MIN, BOT_MAX)
        thresholded_image = cv2.medianBlur(thresholded_image, 15)

        _, contours, hierarchy = cv2.findContours(thresholded_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        if not contours:
            (bot_x, bot_y) = (-1000,-1000)
        else:
            bot = contours[0]
            M = cv2.moments(bot)
            if len(bot) > 2:
                bot_x = int(M['m10']/M['m00'])
                bot_y = int(M['m01']/M['m00'])
            else:
                (bot_x, bot_y) = (-1000,-1000)

        return thresholded_image, (bot_x, bot_y)
page_dewarp.py 文件源码 项目:page_dewarp 作者: mzucker 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def blob_mean_and_tangent(contour):

    moments = cv2.moments(contour)

    area = moments['m00']

    mean_x = moments['m10'] / area
    mean_y = moments['m01'] / area

    moments_matrix = np.array([
        [moments['mu20'], moments['mu11']],
        [moments['mu11'], moments['mu02']]
    ]) / area

    _, svd_u, _ = cv2.SVDecomp(moments_matrix)

    center = np.array([mean_x, mean_y])
    tangent = svd_u[:, 0].flatten().copy()

    return center, tangent
image.py 文件源码 项目:digit-ocr 作者: Nozdi 项目源码 文件源码 阅读 58 收藏 0 点赞 0 评论 0
def insert_into_center(resized_digits):
    results = []
    for img in resized_digits:
        i = np.zeros((28, 28))
        # calculate center of mass of the pixels
        M = cv2.moments(img)
        try:
            xc = M['m10'] / M['m00']
            yc = M['m01'] / M['m00']
        except ZeroDivisionError:
            xc = 10
            yc = 10

        # translating the image so as to position
        # this point at the center of the 28x28 field.
        start_a = max(min(4 + (10 - int(yc)), 8), 0)
        start_b = max(min(4 + (10 - int(xc)), 8), 0)
        i[start_a:start_a+20, start_b:start_b+20] = img

        results.append(i)
    return results
Minimap.py 文件源码 项目:osrmacro 作者: jjvilm 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def find_self():
    low_white = np.array([0,0,255])
    upper_white = np.array([1,255,255])

    mask,mmx, mmy = get_mini_map_mask(low_white,upper_white)

    _, contours, _ = cv2.findContours(mask.copy(), 1,2)

    for cnt in contours:
        M = cv2.moments(cnt)
        print(cv2.contourArea(cnt))
        if cv2.contourArea(cnt) == 4:
            #centroid from img moments
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            print(cx,cy)

    cv2.imshow('img', mask)
    cv2.waitKey(0)
vision.py 文件源码 项目:Vision2016 作者: Team3309 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def moment_score(contour):
    moments = cv2.moments(contour)
    hu = cv2.HuMoments(moments)
    # hu[6] should be close to 0
    return 100 - (hu[6] * 100)
gesture.py 文件源码 项目:Glidr 作者: muinmomin 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
piwall.py 文件源码 项目:piwall-cvtools 作者: infinnovation 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def mapit(self, mode):
        # Find the centroid of the bounding box of the image (we know this by construction - testing the functions)
        w,h,c = self.img.shape
        outerEdge = np.array([(0,0), (0, h), (w,h), (w, 0)], dtype = np.int)
        M = cv2.moments(outerEdge)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        cv2.circle(self.img, (cX, cY), 7, (255, 255, 255), -1)
        cv2.putText(self.img, "center", (cX - 20, cY - 20),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        cv2.rectangle(self.img, (cX-30, cY-30), (cY+30, cY+30),(0,255,0), 2)
ColoredObjectDetector.py 文件源码 项目:robot-camera-platform 作者: danionescu0 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
graph.py 文件源码 项目:skastic 作者: mypalmike 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __init__(self, img_contour, contour):
    self.img_contour = img_contour
    self.contour = contour
    self.children = []
    self.text = None

    # Centroid computation from the opencv docs on contour attributes. (i.e. I have no clue)
    moments = cv2.moments(contour)
    self.centroid = (int(moments['m10']/moments['m00']), int(moments['m01']/moments['m00']))
testing.py 文件源码 项目:retinal-exudates-detection 作者: getsanjeev 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def identify_OD(image):
    newfin = cv2.dilate(image, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations=2)
    mask = np.ones(newfin.shape[:2], dtype="uint8") * 255
    y1, ycontours, yhierarchy = cv2.findContours(newfin.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    prev_contour = ycontours[0]
    for cnt in ycontours:
        if cv2.contourArea(cnt) >= cv2.contourArea(prev_contour):
            prev_contour = cnt
            cv2.drawContours(mask, [cnt], -1, 0, -1)
    M = cv2.moments(prev_contour)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    #print(cx,cy)
    return (cx,cy)
training.py 文件源码 项目:retinal-exudates-detection 作者: getsanjeev 项目源码 文件源码 阅读 64 收藏 0 点赞 0 评论 0
def identify_OD(image):
    newfin = cv2.dilate(image, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations=2)
    mask = np.ones(newfin.shape[:2], dtype="uint8") * 255
    y1, ycontours, yhierarchy = cv2.findContours(newfin.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    prev_contour = ycontours[0]
    for cnt in ycontours:
        if cv2.contourArea(cnt) >= cv2.contourArea(prev_contour):
            prev_contour = cnt
            cv2.drawContours(mask, [cnt], -1, 0, -1)
    M = cv2.moments(prev_contour)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00']) 
    return (cx,cy)
manimouse_gui.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)

# This function helps in filtering the required colored objects from the background
Manimouse_Beta.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)

# This function helps in filtering the required colored objects from the background
click2.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)
twohand.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)

# This function helps in filtering the required colored objects from the background
switch2.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)

# This function helps in filtering the required colored objects from the background
Manimouse.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)

# This function helps in filtering the required colored objects from the background
drag.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)

# This function helps in filtering the required colored objects from the background
scroll.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)

# This function helps in filtering the required colored objects from the background
switch.py 文件源码 项目:Manimouse 作者: shivamkajale 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def drawCentroid(vid, color_area, mask, showCentroid):

    _, contour, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    l=len(contour)
    area = np.zeros(l)

    # filtering contours on the basis of area rane specified globally 
    for i in range(l):
        if cv2.contourArea(contour[i])>color_area[0] and cv2.contourArea(contour[i])<color_area[1]:
            area[i] = cv2.contourArea(contour[i])
        else:
            area[i] = 0

    a = sorted( area, reverse=True) 

    # bringing contours with largest valid area to the top
    for i in range(l):
        for j in range(1):
            if area[i] == a[j]:
                swap( contour, i, j)

    if l > 0 :      
        # finding centroid using method of 'moments'
        M = cv2.moments(contour[0])
        if M['m00'] != 0:
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])
            center = (cx,cy)
            if showCentroid:
                cv2.circle( vid, center, 5, (0,0,255), -1)

            return center
    else:
        # return error handling values
        return (-1,-1)

# This function helps in filtering the required colored objects from the background
omr.py 文件源码 项目:omr 作者: rbaron 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_centroid(contour):
    m = cv2.moments(contour)
    x = int(m["m10"] / m["m00"])
    y = int(m["m01"] / m["m00"])
    return (x, y)
sample_patches_combined.py 文件源码 项目:dream2016_dm 作者: lishen 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def sample_hard_negatives(img, roi_mask, out_dir, img_id, abn,  
                          patch_size=256, neg_cutoff=.35, nb_bkg=100, 
                          start_sample_nb=0,
                          bkg_dir='background', verbose=False):
    '''WARNING: the definition of hns may be problematic.
    There has been study showing that the context of an ROI is also useful
    for classification.
    '''
    bkg_out = os.path.join(out_dir, bkg_dir)
    basename = '_'.join([img_id, str(abn)])

    img = add_img_margins(img, patch_size/2)
    roi_mask = add_img_margins(roi_mask, patch_size/2)
    # Get ROI bounding box.
    roi_mask_8u = roi_mask.astype('uint8')
    ver = (cv2.__version__).split('.')
    if int(ver[0]) < 3:
        contours,_ = cv2.findContours(
            roi_mask_8u.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    else:
        _,contours,_ = cv2.findContours(
            roi_mask_8u.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cont_areas = [ cv2.contourArea(cont) for cont in contours ]
    idx = np.argmax(cont_areas)  # find the largest contour.
    rx,ry,rw,rh = cv2.boundingRect(contours[idx])
    if verbose:
        M = cv2.moments(contours[idx])
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])
        print "ROI centroid=", (cx,cy); sys.stdout.flush()

    rng = np.random.RandomState(12345)
    # Sample hard negative samples.
    sampled_bkg = start_sample_nb
    while sampled_bkg < start_sample_nb + nb_bkg:
        x1,x2 = (rx - patch_size/2, rx + rw + patch_size/2)
        y1,y2 = (ry - patch_size/2, ry + rh + patch_size/2)
        x1 = crop_val(x1, patch_size/2, img.shape[1] - patch_size/2)
        x2 = crop_val(x2, patch_size/2, img.shape[1] - patch_size/2)
        y1 = crop_val(y1, patch_size/2, img.shape[0] - patch_size/2)
        y2 = crop_val(y2, patch_size/2, img.shape[0] - patch_size/2)
        x = rng.randint(x1, x2)
        y = rng.randint(y1, y2)
        if not overlap_patch_roi((x,y), patch_size, roi_mask, cutoff=neg_cutoff):
            patch = img[y - patch_size/2:y + patch_size/2, 
                        x - patch_size/2:x + patch_size/2]
            patch = patch.astype('int32')
            patch_img = toimage(patch, high=patch.max(), low=patch.min(), 
                                mode='I')
            filename = basename + "_%04d" % (sampled_bkg) + ".png"
            fullname = os.path.join(bkg_out, filename)
            patch_img.save(fullname)
            sampled_bkg += 1
            if verbose:
                print "sampled a hns patch at (x,y) center=", (x,y)
                sys.stdout.flush()
sample_patches_combined.py 文件源码 项目:dream2016_dm 作者: lishen 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def sample_blob_negatives(img, roi_mask, out_dir, img_id, abn, blob_detector, 
                          patch_size=256, neg_cutoff=.35, nb_bkg=100, 
                          start_sample_nb=0,
                          bkg_dir='background', verbose=False):
    bkg_out = os.path.join(out_dir, bkg_dir)
    basename = '_'.join([img_id, str(abn)])

    img = add_img_margins(img, patch_size/2)
    roi_mask = add_img_margins(roi_mask, patch_size/2)
    # Get ROI bounding box.
    roi_mask_8u = roi_mask.astype('uint8')
    ver = (cv2.__version__).split('.')
    if int(ver[0]) < 3:
        contours,_ = cv2.findContours(
            roi_mask_8u.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    else:
        _,contours,_ = cv2.findContours(
            roi_mask_8u.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cont_areas = [ cv2.contourArea(cont) for cont in contours ]
    idx = np.argmax(cont_areas)  # find the largest contour.
    rx,ry,rw,rh = cv2.boundingRect(contours[idx])
    if verbose:
        M = cv2.moments(contours[idx])
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])
        print "ROI centroid=", (cx,cy); sys.stdout.flush()

    # Sample blob negative samples.
    key_pts = blob_detector.detect((img/img.max()*255).astype('uint8'))
    rng = np.random.RandomState(12345)
    key_pts = rng.permutation(key_pts)
    sampled_bkg = 0
    for kp in key_pts:
        if sampled_bkg >= nb_bkg:
            break
        x,y = int(kp.pt[0]), int(kp.pt[1])
        if not overlap_patch_roi((x,y), patch_size, roi_mask, cutoff=neg_cutoff):
            patch = img[y - patch_size/2:y + patch_size/2, 
                        x - patch_size/2:x + patch_size/2]
            patch = patch.astype('int32')
            patch_img = toimage(patch, high=patch.max(), low=patch.min(), 
                                mode='I')
            filename = basename + "_%04d" % (start_sample_nb + sampled_bkg) + ".png"
            fullname = os.path.join(bkg_out, filename)
            patch_img.save(fullname)
            if verbose:
                print "sampled a blob patch at (x,y) center=", (x,y)
                sys.stdout.flush()
            sampled_bkg += 1
    return sampled_bkg

#### End of function definition ####
BotTracker.py 文件源码 项目:Pacbot 作者: HarvardURC 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __detect_bot(self, hsv_image):

        # Experimentally determined LED thresholds
        BOT_MIN = np.array([28,8,100], np.uint8)
        BOT_MAX = np.array([32,255,255], np.uint8)

        thresholded_image = cv2.inRange(hsv_image, BOT_MIN, BOT_MAX)
        thresholded_image = cv2.medianBlur(thresholded_image, 15)

        # cv2.imshow('Yellow Tresh', thresholded_image)
        # cv2.waitKey(1)

        contours, hierarchy = cv2.findContours(thresholded_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        if not contours:
            (bot_x, bot_y) = (-1000,-1000)
        else:       
            bot = contours[0]
            M = cv2.moments(bot)
            if len(bot) > 2:
                bot_x = int(M['m10']/M['m00'])
                bot_y = int(M['m01']/M['m00'])
            else:
                bot_x = self.current_location[0]
                bot_y = self.current_location[1]

        return thresholded_image, (bot_x, bot_y)
create_dataset.py 文件源码 项目:keras-autoencoder 作者: Rentier 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
tracking.py 文件源码 项目:ATLeS 作者: liffiton 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _get_centroids(self):
        if not self._contours:
            self._get_contours()

        self._centroids = []

        for contour in self._contours:
            moments = cv2.moments(contour)
            if moments['m00'] != 0.0:  # skip zero-area contours
                centroid_x = moments['m10'] / moments['m00']
                centroid_y = moments['m01'] / moments['m00']
                self._centroids.append((centroid_x, centroid_y))
denseMatter.py 文件源码 项目:osrmacro 作者: jjvilm 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def find_fairy_ring(self):
        run = 1
        while run:
            play_screen = Screenshot.shoot(6,59,510,355,'hsv')
            # finding white on fairy ring inner circle
            low = np.array([107,92,93])
            high = np.array([113,255,129])

            mask = cv2.inRange(play_screen, low, high)

            kernel = np.ones((10,10), np.uint8)
            dilation = cv2.dilate(mask, kernel, iterations = 1)
            #closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

            #_,contours,_ = cv2,findContours(closing.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            _,contours,_ = cv2.findContours(dilation, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

            for con in contours:
                print("Area: {}".format(cv2.contourArea(con)))
                if cv2.contourArea(con) > 1.0:
                    (x, y, w, h) = cv2.boundingRect(con)
                    x += self.rs_x
                    y += self.rs_y
                    x1 = x
                    y1 = y
                    x2 = x + w
                    y2 = y + h
                    print("x1:{} y1:{} x2:{} y2:{}".format(x1,y1,x2,y2))
                    #print(cv2.contourArea(con))
                    #M = cv2.moments(con)
                    # finds centroid
                    #x,y = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
                    Mouse.randMove(x1,y1,x2,y2,3)
                    time.sleep(5)
                    if RS.findOptionClick(x1,y1,'cis'):
                        run = 0
                    time.sleep(2)
                    break

        #cv2.imshow('img', mask)
        #cv2.waitKey(000)


问题


面经


文章

微信
公众号

扫码关注公众号