Python cv2 模块,MORPH_CLOSE 实例源码

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

项目:Speedy-TSLSR    作者:talhaHavadar    | 项目源码 | 文件源码
def __bound_contours(roi):
    """
        returns modified roi(non-destructive) and rectangles that founded by the algorithm.
        @roi region of interest to find contours
        @return (roi, rects)
    """

    roi_copy = roi.copy()
    roi_hsv = cv2.cvtColor(roi, cv2.COLOR_RGB2HSV)
    # filter black color
    mask1 = cv2.inRange(roi_hsv, np.array([0, 0, 0]), np.array([180, 255, 125]))
    mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
    mask1 = cv2.Canny(mask1, 100, 300)
    mask1 = cv2.GaussianBlur(mask1, (1, 1), 0)
    mask1 = cv2.Canny(mask1, 100, 300)

    # mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)))

    # Find contours for detected portion of the image
    im2, cnts, hierarchy = cv2.findContours(mask1.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] # get largest five contour area
    rects = []
    for c in cnts:
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)
        x, y, w, h = cv2.boundingRect(approx)
        if h >= 15:
            # if height is enough
            # create rectangle for bounding
            rect = (x, y, w, h)
            rects.append(rect)
            cv2.rectangle(roi_copy, (x, y), (x+w, y+h), (0, 255, 0), 1);

    return (roi_copy, rects)
项目:reconstruction    作者:microelly2    | 项目源码 | 文件源码
def animpingpong(self):
        obj=self.Object
        img=None
        if not obj.imageFromNode:
            img = cv2.imread(obj.imageFile)
        else:
            print "copy image ..."
            img = obj.imageNode.ViewObject.Proxy.img.copy()
            print "cpied"

        print " loaded"

        # print (obj.blockSize,obj.ksize,obj.k)
#       edges = cv2.Canny(img,obj.minVal,obj.maxVal)
#       color = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
#       edges=color
#

        kernel = np.ones((obj.xsize,obj.ysize),np.uint8)

        closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel, iterations = obj.iterations)


        if True:
            print "zeige"
            cv2.imshow(obj.Label,closing)
            print "gezeigt"
        else:
            from matplotlib import pyplot as plt
            plt.subplot(121),plt.imshow(img,cmap = 'gray')
            plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
            plt.subplot(122),plt.imshow(dst,cmap = 'gray')
            plt.title('Corner Image'), plt.xticks([]), plt.yticks([])
            plt.show()
        print "fertig"
        self.img=closing
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def getContours(img,kernel=(10,10)):

    #Define kernel
    kernel = np.ones(kernel, np.uint8)

    #Open to erode small patches
    thresh = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)

    #Close little holes
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE,kernel, iterations=4)

    #Find contours
    #contours=skimsr.find_contours(thresh,0)

    thresh=thresh.astype('uint8')
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

    areas=[]
    for c in contours:
        areas.append(cv2.contourArea(c))

    return contours,thresh,areas
项目:idmatch    作者:maddevsio    | 项目源码 | 文件源码
def recognize_text(original):
    idcard = original
    gray = cv2.cvtColor(idcard, cv2.COLOR_BGR2GRAY)

    # Morphological gradient:
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    opening = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, kernel)

    # Binarization
    ret, binarization = cv2.threshold(opening, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

    # Connected horizontally oriented regions
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
    connected = cv2.morphologyEx(binarization, cv2.MORPH_CLOSE, kernel)

    # find countours
    _, contours, hierarchy = cv2.findContours(
        connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE
    )
    return contours, hierarchy
项目:tbotnav    作者:patilnabhi    | 项目源码 | 文件源码
def _extract_arm(self, img):
        # find center region of image frame (assume center region is 21 x 21 px)
        center_half = 10 # (=(21-1)/2)  
        center = img[self.height/2 - center_half : self.height/2 + center_half, self.width/2 - center_half : self.width/2 + center_half]

        # determine median depth value
        median_val = np.median(center)

        '''mask the image such that all pixels whose depth values
        lie within a particular range are gray and the rest are black
        '''

        img = np.where(abs(img-median_val) <= self.abs_depth_dev, 128, 0).astype(np.uint8)

        # Apply morphology operation to fill small holes in the image
        kernel = np.ones((5,5), np.uint8)
        img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)

        # Find connected regions (to hand) to remove background objects
        # Use floodfill with a small image area (7 x 7 px) that is set gray color value
        kernel2 = 3
        img[self.height/2-kernel2:self.height/2+kernel2, self.width/2-kernel2:self.width/2+kernel2] = 128

        # a black mask to mask the 'non-connected' components black
        mask = np.zeros((self.height + 2, self.width + 2), np.uint8)
        floodImg = img.copy()

        # Use floodFill function to paint the connected regions white 
        cv2.floodFill(floodImg, mask, (self.width/2, self.height/2), 255, flags=(4 | 255 << 8))

        # apply a binary threshold to show only connected hand region
        ret, floodedImg = cv2.threshold(floodImg, 129, 255, cv2.THRESH_BINARY)

        return floodedImg
项目:image_text_reader    作者:yardstick17    | 项目源码 | 文件源码
def remove_noise_and_smooth(file_name):
    logging.info('Removing noise and smoothening image')
    img = cv2.imread(file_name, 0)
    filtered = cv2.adaptiveThreshold(img.astype(np.uint8), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 41, 3)
    kernel = np.ones((1, 1), np.uint8)
    opening = cv2.morphologyEx(filtered, cv2.MORPH_OPEN, kernel)
    closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)
    img = image_smoothening(img)
    or_image = cv2.bitwise_or(img, closing)
    return or_image
项目:osrmacro    作者:jjvilm    | 项目源码 | 文件源码
def isInvEmpty():
    bag, bagx,bagy = get_bag('bag and coords', 'hsv')
    # looks for color of empty inv
    low = np.array([10,46,58])
    high= np.array([21,92,82])
    # applies mask
    mask = cv2.inRange(bag, low, high)
    # removes any noise
    kernel = np.ones((5,5), np.uint8)
    closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

    # looks to see if the inv is all white pixels
    # returns true, else False
    if (closing.view() == 255).all():
        return True
    return False
项目:document-layout-analysis    作者:rbaguila    | 项目源码 | 文件源码
def process_letter(thresh,output):  
    # assign the kernel size    
    kernel = np.ones((2,1), np.uint8) # vertical
    # use closing morph operation then erode to narrow the image    
    temp_img = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,kernel,iterations=3)
    # temp_img = cv2.erode(thresh,kernel,iterations=2)      
    letter_img = cv2.erode(temp_img,kernel,iterations=1)

    # find contours 
    (contours, _) = cv2.findContours(letter_img.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    # loop in all the contour areas
    for cnt in contours:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(output,(x-1,y-5),(x+w,y+h),(0,255,0),1)

    return output   


#processing letter by letter boxing
项目:document-layout-analysis    作者:rbaguila    | 项目源码 | 文件源码
def process_word(thresh,output):    
    # assign 2 rectangle kernel size 1 vertical and the other will be horizontal    
    kernel = np.ones((2,1), np.uint8)
    kernel2 = np.ones((1,4), np.uint8)
    # use closing morph operation but fewer iterations than the letter then erode to narrow the image   
    temp_img = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,kernel,iterations=2)
    #temp_img = cv2.erode(thresh,kernel,iterations=2)   
    word_img = cv2.dilate(temp_img,kernel2,iterations=1)

    (contours, _) = cv2.findContours(word_img.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    for cnt in contours:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(output,(x-1,y-5),(x+w,y+h),(0,255,0),1)

    return output   

#processing line by line boxing
项目:document-layout-analysis    作者:rbaguila    | 项目源码 | 文件源码
def process_line(thresh,output):    
    # assign a rectangle kernel size    1 vertical and the other will be horizontal
    kernel = np.ones((1,5), np.uint8)
    kernel2 = np.ones((2,4), np.uint8)  
    # use closing morph operation but fewer iterations than the letter then erode to narrow the image   
    temp_img = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,kernel2,iterations=2)
    #temp_img = cv2.erode(thresh,kernel,iterations=2)   
    line_img = cv2.dilate(temp_img,kernel,iterations=5)

    (contours, _) = cv2.findContours(line_img.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    for cnt in contours:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(output,(x-1,y-5),(x+w,y+h),(0,255,0),1)

    return output   

#processing par by par boxing
项目:TableSoccerCV    作者:StudentCV    | 项目源码 | 文件源码
def _smooth_ball_mask(self, mask):
        """
        The mask created inDetectBallPosition might be noisy.
        :param mask: The mask to smooth (Image with bit depth 1)
        :return: The smoothed mask
        """
        # create the disk-shaped kernel for the following image processing,
        r = 3
        kernel = np.ones((2*r, 2*r), np.uint8)
        for x in range(0, 2*r):
            for y in range(0, 2*r):
                if(x - r + 0.5)**2 + (y - r + 0.5)**2 > r**2:
                    kernel[x, y] = 0

        # remove noise
        # see http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

        return mask
项目:TableSoccerCV    作者:StudentCV    | 项目源码 | 文件源码
def SmoothFieldMask(self, mask):
        # erst Close und dann DILATE führt zu guter Erkennung der Umrandung oben

        kernel = np.ones((20,20),np.uint8)


        kernel = np.ones((5,5),np.uint8)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
        #kernel = np.ones((20,20),np.uint8)
    #mask = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)
        #kernel = np.ones((20,20),np.uint8)

        mask = cv2.GaussianBlur(mask,(11,11),0)

        #mask = cv2.morphologyEx(mask, cv2.MORPH_ERODE, kernel)

    #    plt.imshow(cv2.cvtColor(cv2.bitwise_and(self.ImgHSV,self.ImgHSV,mask=mask),cv2.COLOR_HSV2RGB),cmap="gray")
     #   plt.show()

        return mask
项目:hazcam    作者:alex-sherman    | 项目源码 | 文件源码
def update_edge_mask(self, previous_mask, previous_line, slope_sign, thrs1, thrs2, debug):
        lines = cv2.HoughLinesP(self.edge, 1, np.pi / 180, 70, minLineLength = 10, maxLineGap = 200)
        lines = filter_lines(lines, self.vanishing_height, self.edge.shape[0], slope_sign)
        self.lines.extend(lines)
        mask = np.zeros(self.edge.shape, np.uint8)
        for line in lines:
            x1,y1,x2,y2 = line
            cv2.line(mask, (x1,y1),(x2,y2), 255, MASK_WIDTH)
        mask = cv2.addWeighted(mask, MASK_WEIGHT, previous_mask, 1 - MASK_WEIGHT, 0)
        #self.current_mask *= int(255.0 / self.current_mask.max())
        previous_mask = mask.copy()
        _, mask = cv2.threshold(mask, 40, 255, cv2.THRESH_BINARY)
        masked_edges = cv2.morphologyEx(cv2.bitwise_and(self.edge, self.edge, mask = mask), cv2.MORPH_CLOSE, np.array([[1] * EDGE_DILATION] *EDGE_DILATION))
        lines2 = cv2.HoughLinesP(masked_edges, 1, np.pi / 180, 70, minLineLength = 10, maxLineGap = 200)
        lines2 = filter_lines(lines2, self.vanishing_height, self.edge.shape[0], slope_sign)
        self.lines2.extend(lines2)
        for line in lines2:
            x1,y1,x2,y2 = line
            cv2.line(mask, (x1,y1),(x2,y2), 255, MASK_WIDTH)
            previous_line[0] = add(previous_line[0], (x2,y2))
            previous_line[1] = add(previous_line[1], (x_at_y(self.edge.shape[0]*0.6, x1, y1, x2, y2), self.edge.shape[0]*0.6))
        previous_line[0] = scale(previous_line[0], 1.0 / (len(lines2) + 1))
        previous_line[1] = scale(previous_line[1], 1.0 / (len(lines2) + 1))
        return masked_edges, mask, previous_mask, previous_line
项目:reconstruction    作者:microelly2    | 项目源码 | 文件源码
def execute_Morphing(proxy,obj):

    try: img=obj.sourceObject.Proxy.img.copy()
    except: img=cv2.imread(__dir__+'/icons/freek.png')

    ks=obj.kernel
    kernel = np.ones((ks,ks),np.uint8)
    if obj.filter == 'dilation':
        dilation = cv2.dilate(img,kernel,iterations = 1)
        img=dilation
    if obj.filter == 'erosion':
        dilation = cv2.erode(img,kernel,iterations = 1)
        img=dilation
    if obj.filter == 'opening':
        dilation = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
        img=dilation
    if obj.filter == 'closing':
        dilation = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
        img=dilation

    obj.Proxy.img = img



#
# property functions for HoughLines
#
项目:piwall-cvtools    作者:infinnovation    | 项目源码 | 文件源码
def denoise_foreground(img, fgmask):
    img_bw = 255*(fgmask > 5).astype('uint8')
    se1 = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    se2 = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
    mask = cv2.morphologyEx(img_bw, cv2.MORPH_CLOSE, se1)
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se2)
    mask = np.dstack([mask, mask, mask]) / 255
    img_dn = img * mask
    return img_dn
项目:cervix-roi-segmentation-by-unet    作者:scottykwok    | 项目源码 | 文件源码
def cv2_morph_close(binary_image, size=5):
    import cv2
    from skimage.morphology import disk
    kernel = disk(size)
    result = cv2.morphologyEx(binary_image, cv2.MORPH_CLOSE, kernel)
    return result
项目:pycolor_detection    作者:parth1993    | 项目源码 | 文件源码
def closing(mask):
    assert isinstance(mask, numpy.ndarray), 'mask must be a numpy array'
    assert mask.ndim == 2, 'mask must be a greyscale image'
    logger.debug("closing mask of shape {0}".format(mask.shape))

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)

    return mask
项目:BlurDetection    作者:whdcumt    | 项目源码 | 文件源码
def morphology(msk):
    assert isinstance(msk, numpy.ndarray), 'msk must be a numpy array'
    assert msk.ndim == 2, 'msk must be a greyscale image'
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    msk = cv2.erode(msk, kernel, iterations=1)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    msk = cv2.morphologyEx(msk, cv2.MORPH_CLOSE, kernel)
    msk[msk < 128] = 0
    msk[msk > 127] = 255
    return msk
项目:retinal-exudates-detection    作者:getsanjeev    | 项目源码 | 文件源码
def extract_bv(image):          
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    contrast_enhanced_green_fundus = clahe.apply(image)
    # applying alternate sequential filtering (3 times closing opening)
    r1 = cv2.morphologyEx(contrast_enhanced_green_fundus, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
    R1 = cv2.morphologyEx(r1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
    r2 = cv2.morphologyEx(R1, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
    R2 = cv2.morphologyEx(r2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
    r3 = cv2.morphologyEx(R2, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
    R3 = cv2.morphologyEx(r3, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
    f4 = cv2.subtract(R3,contrast_enhanced_green_fundus)
    f5 = clahe.apply(f4)

    # removing very small contours through area parameter noise removal
    ret,f6 = cv2.threshold(f5,15,255,cv2.THRESH_BINARY)
    mask = np.ones(f5.shape[:2], dtype="uint8") * 255
    im2, contours, hierarchy = cv2.findContours(f6.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        if cv2.contourArea(cnt) <= 200:
            cv2.drawContours(mask, [cnt], -1, 0, -1)            
    im = cv2.bitwise_and(f5, f5, mask=mask)
    ret,fin = cv2.threshold(im,15,255,cv2.THRESH_BINARY_INV)            
    newfin = cv2.erode(fin, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)   

    # removing blobs of microaneurysm & unwanted bigger chunks taking in consideration they are not straight lines like blood
    # vessels and also in an interval of area
    fundus_eroded = cv2.bitwise_not(newfin)
    xmask = np.ones(image.shape[:2], dtype="uint8") * 255
    x1, xcontours, xhierarchy = cv2.findContours(fundus_eroded.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)    
    for cnt in xcontours:
        shape = "unidentified"
        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.04 * peri, False)
        if len(approx) > 4 and cv2.contourArea(cnt) <= 3000 and cv2.contourArea(cnt) >= 100:
            shape = "circle"    
        else:
            shape = "veins"
        if(shape=="circle"):
            cv2.drawContours(xmask, [cnt], -1, 0, -1)   

    finimage = cv2.bitwise_and(fundus_eroded,fundus_eroded,mask=xmask)  
    blood_vessels = cv2.bitwise_not(finimage)
    dilated = cv2.erode(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)), iterations=1)
    #dilated1 = cv2.dilate(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
    blood_vessels_1 = cv2.bitwise_not(dilated)
    return blood_vessels_1
项目:retinal-exudates-detection    作者:getsanjeev    | 项目源码 | 文件源码
def extract_bv(image):
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    contrast_enhanced_green_fundus = clahe.apply(image)
    # applying alternate sequential filtering (3 times closing opening)
    r1 = cv2.morphologyEx(contrast_enhanced_green_fundus, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
    R1 = cv2.morphologyEx(r1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
    r2 = cv2.morphologyEx(R1, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
    R2 = cv2.morphologyEx(r2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
    r3 = cv2.morphologyEx(R2, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
    R3 = cv2.morphologyEx(r3, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
    f4 = cv2.subtract(R3,contrast_enhanced_green_fundus)
    f5 = clahe.apply(f4)

    # removing very small contours through area parameter noise removal
    ret,f6 = cv2.threshold(f5,15,255,cv2.THRESH_BINARY)
    mask = np.ones(f5.shape[:2], dtype="uint8") * 255
    im2, contours, hierarchy = cv2.findContours(f6.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        if cv2.contourArea(cnt) <= 200:
            cv2.drawContours(mask, [cnt], -1, 0, -1)            
    im = cv2.bitwise_and(f5, f5, mask=mask)
    ret,fin = cv2.threshold(im,15,255,cv2.THRESH_BINARY_INV)            
    newfin = cv2.erode(fin, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)   

    # removing blobs of microaneurysm & unwanted bigger chunks taking in consideration they are not straight lines like blood
    # vessels and also in an interval of area
    fundus_eroded = cv2.bitwise_not(newfin)
    xmask = np.ones(image.shape[:2], dtype="uint8") * 255
    x1, xcontours, xhierarchy = cv2.findContours(fundus_eroded.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)    
    for cnt in xcontours:
        shape = "unidentified"
        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.04 * peri, False)
        if len(approx) > 4 and cv2.contourArea(cnt) <= 3000 and cv2.contourArea(cnt) >= 100:
            shape = "circle"    
        else:
            shape = "veins"
        if(shape=="circle"):
            cv2.drawContours(xmask, [cnt], -1, 0, -1)   

    finimage = cv2.bitwise_and(fundus_eroded,fundus_eroded,mask=xmask)  
    blood_vessels = cv2.bitwise_not(finimage)
    dilated = cv2.erode(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)), iterations=1)
    #dilated1 = cv2.dilate(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
    blood_vessels_1 = cv2.bitwise_not(dilated)
    return blood_vessels_1
项目:2017-robot    作者:frc1418    | 项目源码 | 文件源码
def threshold(self, img):
        cv2.cvtColor(img, cv2.COLOR_BGR2HSV, dst=self.hsv)
        cv2.inRange(self.hsv, self.thresh_low, self.thresh_high, dst=self.bin)

        cv2.morphologyEx(self.bin, cv2.MORPH_CLOSE, self.morphKernel, dst=self.bin2, iterations=1)

        if self.draw_thresh:
            b = (self.bin2 != 0)
            cv2.copyMakeBorder(self.black, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=self.RED, dst=self.out)
            self.out[np.dstack((b, b, b))] = 255

        return self.bin2
项目:unet-tensorflow    作者:timctho    | 项目源码 | 文件源码
def CloseInContour( mask, element ):
    large = 0
    result = mask
    _, contours, _ = cv2.findContours(result,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    #find the biggest area
    c = max(contours, key = cv2.contourArea)

    closing = cv2.morphologyEx(result, cv2.MORPH_CLOSE, element)
    for x in range(mask.shape[0]):
        for y in range(mask.shape[1]):
             pt = cv2.pointPolygonTest(c, (x, y), True)
             #pt = cv2.pointPolygonTest(c, (x, y), False)
             if pt > 3:
                result[x][y] = closing[x][y]
    return result.astype(np.float32)
项目:unet-tensorflow    作者:timctho    | 项目源码 | 文件源码
def CloseInContour( mask, element ):
        large = 0
        result = mask
        _, contours, _ = cv2.findContours(result,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
        #find the biggest area
        c = max(contours, key = cv2.contourArea)

        closing = cv2.morphologyEx(result, cv2.MORPH_CLOSE, element)
        for x in range(mask.shape[0]):
            for y in range(mask.shape[1]):
                 #pt = cv2.pointPolygonTest(c, (x, y), True)
                 pt = cv2.pointPolygonTest(c, (x, y), False)
                 if pt == 1:
                    result[x][y] = closing[x][y]
        return result.astype(np.float32)
项目:ghetto_omr    作者:pohzhiee    | 项目源码 | 文件源码
def outlining(img):
    #kernel size
    kernel_size=3
    #-------------------------------------------------
    #bilateral filter, sharpen, thresh image
    biblur=cv2.bilateralFilter(img,20,175,175)
    sharp=cv2.addWeighted(img,1.55,biblur,-0.5,0)
    ret1,thresh1 = cv2.threshold(sharp,127,255,cv2.THRESH_OTSU)

    #negative and closed image
    inv=cv2.bitwise_not(thresh1)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
    closed = cv2.morphologyEx(inv, cv2.MORPH_CLOSE, kernel)
    return closed
项目:dust_repos    作者:taozhijiang    | 项目源码 | 文件源码
def img_contour_extra(im):
    # ?????
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(13,7))
    bgmask = cv2.morphologyEx(im, cv2.MORPH_CLOSE, kernel)

    img_show_hook("??????", bgmask)

    # ??????
    # ??????????
    im2, contours, hierarchy = cv2.findContours(bgmask.copy(), cv2.RETR_EXTERNAL, #????
                                cv2.CHAIN_APPROX_SIMPLE)
    return contours
项目:dust_repos    作者:taozhijiang    | 项目源码 | 文件源码
def img_contour_extra(im):
    # ?????
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(13,7))
    bgmask = cv2.morphologyEx(im, cv2.MORPH_CLOSE, kernel)

    img_show_hook("??????", bgmask)

    # ??????
    # ??????????
    im2, contours, hierarchy = cv2.findContours(bgmask.copy(), cv2.RETR_EXTERNAL, #????
                                cv2.CHAIN_APPROX_SIMPLE)
    return contours
项目:opencv-helpers    作者:abarrak    | 项目源码 | 文件源码
def fill(image, kernel=(2, 2)):
  ''' fill gaps in shapes structure. '''
  return cv.morphologyEx(image, cv.MORPH_CLOSE, kernel)
项目:UAV-and-TrueOrtho    作者:LeonChen66    | 项目源码 | 文件源码
def closing(img, kernel_size):
    kernel = np.ones((kernel_size, kernel_size), np.uint8)
    closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    return closing
项目:UAV-and-TrueOrtho    作者:LeonChen66    | 项目源码 | 文件源码
def closing(img,kernel_size):
    kernel = np.ones((kernel_size,kernel_size),np.uint8)
    closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    return closing
项目:pynephoscope    作者:neXyon    | 项目源码 | 文件源码
def close_result(self, result):
        return cv2.morphologyEx(result, cv2.MORPH_CLOSE, self.kernel)
项目:DoNotSnap    作者:AVGInnovationLabs    | 项目源码 | 文件源码
def roiMask(image, boundaries):
    scale = max([1.0, np.average(np.array(image.shape)[0:2] / 400.0)])
    shape = (int(round(image.shape[1] / scale)), int(round(image.shape[0] / scale)))

    small_color = cv2.resize(image, shape, interpolation=cv2.INTER_LINEAR)

    # reduce details and remove noise for better edge detection
    small_color = cv2.bilateralFilter(small_color, 8, 64, 64)
    small_color = cv2.pyrMeanShiftFiltering(small_color, 8, 64, maxLevel=1)
    small = cv2.cvtColor(small_color, cv2.COLOR_BGR2HSV)

    hue = small[::, ::, 0]
    intensity = cv2.cvtColor(small_color, cv2.COLOR_BGR2GRAY)

    edges = extractEdges(hue, intensity)
    roi = roiFromEdges(edges)
    weight_map = weightMap(hue, intensity, edges, roi)

    _, final_mask = cv2.threshold(roi, 5, 255, cv2.THRESH_BINARY)
    small = cv2.bitwise_and(small, small, mask=final_mask)

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))

    for (lower, upper) in boundaries:
        lower = np.array([lower, 80, 50], dtype="uint8")
        upper = np.array([upper, 255, 255], dtype="uint8")

        # find the colors within the specified boundaries and apply
        # the mask
        mask = cv2.inRange(small, lower, upper)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
        final_mask = cv2.bitwise_and(final_mask, mask)

    # blur the mask for better contour extraction
    final_mask = cv2.GaussianBlur(final_mask, (5, 5), 0)
    return (final_mask, weight_map, scale)
项目:cancer_nn    作者:tanmoyopenroot    | 项目源码 | 文件源码
def getClosingImage(img):
    kernel = np.ones((35,35),np.uint8)
    closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    return closing
项目:deep_ocr    作者:JinpengLI    | 项目源码 | 文件源码
def check_if_good_boundary(self, boundary, norm_height, norm_width, color_img):
        preprocess_bg_mask = PreprocessBackgroundMask(boundary)
        char_w = norm_width / 20
        remove_noise = PreprocessRemoveNonCharNoise(char_w)

        id_card_img_mask = preprocess_bg_mask.do(color_img)
        id_card_img_mask[0:int(norm_height*0.05),:] = 0
        id_card_img_mask[int(norm_height*0.95): ,:] = 0
        id_card_img_mask[:, 0:int(norm_width*0.05)] = 0
        id_card_img_mask[:, int(norm_width*0.95):] = 0

        remove_noise.do(id_card_img_mask)

#        se1 = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
#        se2 = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
#        mask = cv2.morphologyEx(id_card_img_mask, cv2.MORPH_CLOSE, se1)
#        id_card_img_mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se2)
#  
        ## remove right head profile
        left_half_id_card_img_mask = np.copy(id_card_img_mask)
        left_half_id_card_img_mask[:, norm_width/2:] = 0

        ## Try to find text lines and chars
        horizontal_sum = np.sum(left_half_id_card_img_mask, axis=1)
        line_ranges = extract_peek_ranges_from_array(horizontal_sum)

        return len(line_ranges) >= 5 and len(line_ranges) <= 7
项目:Simple-deCAPTCHA    作者:BLKStone    | 项目源码 | 文件源码
def preprocess(self):
        self.resizeCaptcha()
        # ???
        img_thresh = self.th1(self.img)

        if self.m_debug:
            cv2.imshow("thres", img_thresh)
            cv2.imwrite("debug/threshold.png", img_thresh)

        # ????? ???
        kernel = np.ones((2,2),np.uint8)
        closing = cv2.morphologyEx(img_thresh , cv2.MORPH_CLOSE, kernel)

        if self.m_debug:
            cv2.imshow("close", closing)
            cv2.imwrite("debug/closing.png",closing)

        # ????
        constant = cv2.copyMakeBorder(closing ,50,50,50,50,cv2.BORDER_CONSTANT,value=255)

        # ??????? 0 ? 255??
        # inverse binary image
        # constant = self.inverseColor(constant)

        # ??
        constantSrc = cv2.merge((constant,constant,constant))

        if self.m_debug:
            cv2.imwrite("debug/broader.png",constantSrc)

        self.imgPreprocess = constantSrc.copy()
项目:R-CNN_LIGHT    作者:YeongHyeon    | 项目源码 | 文件源码
def closing(binary_img=None, k_size=2, iterations=1):

    kernel = np.ones((k_size, k_size), np.uint8)

    return cv2.morphologyEx(binary_img, cv2.MORPH_CLOSE, kernel, iterations=iterations) # iteration = loop
项目:osrmacro    作者:jjvilm    | 项目源码 | 文件源码
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)
项目:remho    作者:teamresistance    | 项目源码 | 文件源码
def morph_close(image, kernel_x=5, kernel_y=1):
        # Attempt to connect adjacent contours by dilating and then eroding
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_x, kernel_y))
        image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)
        return image
项目:SharkCV    作者:hammerhead226    | 项目源码 | 文件源码
def close(self, **kwargs):
        if 'shape' not in kwargs:
            kwargs['shape'] = cv2.MORPH_ELLIPSE
        if 'size' not in kwargs:
            kwargs['size'] = 3
        if kwargs['size'] > 0:
            kernel = cv2.getStructuringElement(kwargs['shape'], (kwargs['size'], kwargs['size']))
            self._ndarray = cv2.morphologyEx(self.ndarray, cv2.MORPH_CLOSE, kernel)
            self._contours = None

    # AND this frame with another frame
项目:Vec-Lib    作者:vladan-jovicic    | 项目源码 | 文件源码
def detect_contours(self):
        blurred = cv2.GaussianBlur(self.src, (self.kernel_size, self.kernel_size), self.sigma)

        # apply canny detector
        detected_edges = cv2.Canny(blurred, self.threshold, self.threshold * self.ratio, apertureSize=self.apertureSize, L2gradient=True)

        if self.use_dilate:
            kernel = np.ones((3, 3), np.uint8)
            detected_edges = cv2.morphologyEx(detected_edges, cv2.MORPH_CLOSE, kernel)

        self.contours_img, self.simple_contours, self.hierarchy = cv2.findContours(detected_edges.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS)
        # pdb.gimp_message(self.hierarchy)
        _, self.full_contours, _ = cv2.findContours(detected_edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
项目:BirdCLEF2017    作者:kahst    | 项目源码 | 文件源码
def hasBird(spec, threshold=16):

    #working copy
    img = spec.copy()

    #STEP 1: Median blur
    img = cv2.medianBlur(img,5)

    #STEP 2: Median threshold
    col_median = np.median(img, axis=0, keepdims=True)
    row_median = np.median(img, axis=1, keepdims=True)

    img[img < row_median * 3] = 0
    img[img < col_median * 4] = 0
    img[img > 0] = 1

    #STEP 3: Remove singles
    img = filter_isolated_cells(img, struct=np.ones((3,3)))

    #STEP 4: Morph Closing
    img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, np.ones((5,5), np.float32))

    #STEP 5: Frequency crop
    img = img[128:-16, :]

    #STEP 6: Count columns and rows with signal
    #(Note: We only use rows with signal as threshold, but columns might come in handy in other scenarios)

    #column has signal?
    col_max = np.max(img, axis=0)
    col_max = ndimage.morphology.binary_dilation(col_max, iterations=2).astype(col_max.dtype)
    cthresh = col_max.sum()

    #row has signal?
    row_max = np.max(img, axis=1)
    row_max = ndimage.morphology.binary_dilation(row_max, iterations=2).astype(row_max.dtype)
    rthresh = row_max.sum()

    #final threshold
    thresh = rthresh

    #DBUGB: show?
    #print thresh
    #cv2.imshow('BIRD?', img)
    #cv2.waitKey(-1)

    #STEP 7: Apply threshold (Default = 16)
    bird = True
    if thresh < threshold:
        bird = False

    return bird, thresh

######################################################

#elist all bird species
项目:Automatic-Plate-Number-Recognition-APNR    作者:kagan94    | 项目源码 | 文件源码
def find_contours(img):
    '''
    :param img: (numpy array)
    :return: all possible rectangles (contours)
    '''
    img_blurred = cv2.GaussianBlur(img, (5, 5), 1)  # remove noise
    img_gray = cv2.cvtColor(img_blurred, cv2.COLOR_BGR2GRAY)  # greyscale image
    # cv2.imshow('', img_gray)
    # cv2.waitKey(0)

    # Apply Sobel filter to find the vertical edges
    # Find vertical lines. Car plates have high density of vertical lines
    img_sobel_x = cv2.Sobel(img_gray, cv2.CV_8UC1, dx=1, dy=0, ksize=3, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT)
    # cv2.imshow('img_sobel', img_sobel_x)

    # Apply optimal threshold by using Oslu algorithm
    retval, img_threshold = cv2.threshold(img_sobel_x, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
    # cv2.imshow('s', img_threshold)
    # cv2.waitKey(0)

    # TODO: Try to apply AdaptiveThresh
    # Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
    # gaus_threshold = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 115, 1)
    # cv2.imshow('or', img)
    # cv2.imshow('gaus', gaus_threshold)
    # cv2.waitKey(0)

    # Define a stuctural element as rectangular of size 17x3 (we'll use it during the morphological cleaning)
    element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(17, 3))

    # And use this structural element in a close morphological operation
    morph_img_threshold = deepcopy(img_threshold)
    cv2.morphologyEx(src=img_threshold, op=cv2.MORPH_CLOSE, kernel=element, dst=morph_img_threshold)
    # cv2.dilate(img_threshold, kernel=np.ones((1,1), np.uint8), dst=img_threshold, iterations=1)
    # cv2.imshow('Normal Threshold', img_threshold)
    # cv2.imshow('Morphological Threshold based on rect. mask', morph_img_threshold)
    # cv2.waitKey(0)

    # Find contours that contain possible plates (in hierarchical relationship)
    contours, hierarchy = cv2.findContours(morph_img_threshold,
                                           mode=cv2.RETR_EXTERNAL,  # retrieve the external contours
                                           method=cv2.CHAIN_APPROX_NONE)  # all pixels of each contour

    plot_intermediate_steps = False
    if plot_intermediate_steps:
        plot(plt, 321, img, "Original image")
        plot(plt, 322, img_blurred, "Blurred image")
        plot(plt, 323, img_gray, "Grayscale image", cmap='gray')
        plot(plt, 324, img_sobel_x, "Sobel")
        plot(plt, 325, img_threshold, "Threshold image")
        # plot(plt, 326, morph_img_threshold, "After Morphological filter")
        plt.tight_layout()
        plt.show()

    return contours
项目:dust_repos    作者:taozhijiang    | 项目源码 | 文件源码
def img_tesseract_detect(c_rect, im):
    # ????minAreaRect??????-90~0??????????????????
    # ???????????????????????????????????????
    pts = c_rect.reshape(4, 2)
    rect = np.zeros((4, 2), dtype = "float32")

    # the top-left point has the smallest sum whereas the
    # bottom-right has the largest sum
    s = pts.sum(axis = 1)
    rect[0] = pts[np.argmin(s)]
    rect[3] = pts[np.argmax(s)]

    # compute the difference between the points -- the top-right
    # will have the minumum difference and the bottom-left will
    # have the maximum difference
    diff = np.diff(pts, axis = 1)
    rect[2] = pts[np.argmin(diff)]
    rect[1] = pts[np.argmax(diff)]    

    dst = np.float32([[0,0],[0,100],[200,0],[200,100]])

    M = cv2.getPerspectiveTransform(rect, dst)
    warp = cv2.warpPerspective(im, M, (200, 100))

    img_show_hook("??????", warp) 

    warp = np.array(warp, dtype=np.uint8)
    radius = 10
    selem = disk(radius)

    #????????OTSU????
    local_otsu = rank.otsu(warp, selem)
    l_otsu = np.uint8(warp >= local_otsu)
    l_otsu *= 255

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(4, 4))
    l_otsu = cv2.morphologyEx(l_otsu, cv2.MORPH_CLOSE, kernel)    

    img_show_hook("?????OTSU??", l_otsu) 

    print("?????")
    print(pytesseract.image_to_string(Image.fromarray(l_otsu)))

    cv2.waitKey(0)
    return
项目:dust_repos    作者:taozhijiang    | 项目源码 | 文件源码
def img_tesseract_detect(c_rect, im):
    # ????minAreaRect??????-90~0??????????????????
    # ???????????????????????????????????????
    pts = c_rect.reshape(4, 2)
    rect = np.zeros((4, 2), dtype = "float32")

    # the top-left point has the smallest sum whereas the
    # bottom-right has the largest sum
    s = pts.sum(axis = 1)
    rect[0] = pts[np.argmin(s)]
    rect[3] = pts[np.argmax(s)]

    # compute the difference between the points -- the top-right
    # will have the minumum difference and the bottom-left will
    # have the maximum difference
    diff = np.diff(pts, axis = 1)
    rect[2] = pts[np.argmin(diff)]
    rect[1] = pts[np.argmax(diff)]    

    width = rect[3][0] - rect[0][0]
    height = rect[3][1] - rect[0][1]

    width = (int)((50.0 / height) * width)
    height = 50

    dst = np.float32([[0,0],[0,height],[width,0],[width,height]])

    M = cv2.getPerspectiveTransform(rect, dst)
    warp = cv2.warpPerspective(im, M, (width, height))

    img_show_hook("??????", warp) 

    warp = np.array(warp, dtype=np.uint8)
    radius = 13
    selem = disk(radius)

    #????????OTSU????
    local_otsu = rank.otsu(warp, selem)
    l_otsu = np.uint8(warp >= local_otsu)
    l_otsu *= 255

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(2,2))
    l_otsu = cv2.morphologyEx(l_otsu, cv2.MORPH_CLOSE, kernel)    

    img_show_hook("?????OTSU??", l_otsu) 

    print("?????")
    print(pytesseract.image_to_string(Image.fromarray(l_otsu), lang="chi-sim"))

    cv2.waitKey(0)
    return
项目: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 pink objects in the image
      lower_pink = numpy.array([139, 0, 240], numpy.uint8)
      upper_pink = numpy.array([159, 121, 255], numpy.uint8)
      mask = cv2.inRange(hsv, lower_pink, upper_pink)

      # 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 target found
      if self.contourLength < 1:
         print "No target found"

      else:                       # target found

         ## 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])

         #### Target #### the largest "pink" object
         target_image = contours[area.index(max(area))]

         # Using moments find the center of the object and draw a red outline around the object
         target_m = cv2.moments(target_image)
         self.target_u = int(target_m['m10']/target_m['m00'])
         self.target_v = int(target_m['m01']/target_m['m00'])
         points = cv2.minAreaRect(target_image)
         box = cv2.cv.BoxPoints(points)
         box = numpy.int0(box)
         cv2.drawContours(image, [box], 0, (0, 0, 255), 2)
         rospy.loginfo("Center of target is x at %d and y at %d", int(self.target_u), int(self.target_v))

         self.target_found = True               # set flag for depth_callback processing

         # show image with target outlined with a red rectangle
         cv2.imshow ("Target", 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 pink target.
项目: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.
项目:osrmacro    作者:jjvilm    | 项目源码 | 文件源码
def find_bank_booth():
    """Finds bank booth and clicks it.  Returns True if found, else False"""

    bank_booth_glass_window = ([0,72,149],[179,82,163])
    # take screenshot of playing area
    play_area_screen,psx,psy = getPlayingScreen()

    # find glasswindow for bankbooth
    mask = cv2.inRange(play_area_screen, np.array(bank_booth_glass_window[0]), np.array(bank_booth_glass_window[1]))

    # gets RS window's position
    rsx,rsy = position()

    psx += rsx
    psy += rsy

    kernel = np.ones((3,3), np.uint8)
    closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)


    #cv2.imshow('img', closing)
    #cv2.waitKey(0)

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

    try:
        for con in contours:
            if cv2.contourArea(con) > 10:
                #print(cv2.contourArea(con))
                M = cv2.moments(con)
                # finds centroid
                cx,cy = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
                psx += cx
                psy += cy
                # adds randomness to coords
                psx += random.randint(-7,7)
                psy += random.randint(-7,7)

                #move click
                Mouse.moveClick(psx,psy,1)
                RandTime.randTime(0,0,0,0,9,9)
                return 1
    except Exception as e:
        print("Bank NOT found!\nMove camera around!")
    # returns False if bank not found
    return 0
项目:osrmacro    作者:jjvilm    | 项目源码 | 文件源码
def find_motherload_mine():
    """Returns mine's location x, and y coords"""
    play_img,psx,psy = RS.getPlayingScreen()


    mines = {
        0: (np.array([0,0,153]), np.array([8,25,209])),
        1: (np.array([0,0,72]), np.array([2,25,144]))
    }

    for mine_key  in mines.keys():
        #print("Mine: {}".format(mine_key))
        lower = mines[mine_key][0]
        upper = mines[mine_key][1]

        mask = cv2.inRange(play_img, lower, upper)

        kernel = np.ones((10,10), np.uint8)

        closing  =  cv2.morphologyEx(mask.copy(), cv2.MORPH_CLOSE, kernel)


        #cv2.imshow('mask', mask)
        #cv2.imshow('closing', closing)
        #cv2.waitKey(0)

        _, contours, _ = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        if contours[0].any():
            pass
        else:
            print('didnt find contours')
            break

        for con in contours[::-1]:
            M = cv2.moments(con)
            if cv2.contourArea(con) > 20:
                # Shows the mask

                #centroid from img moments
                cx = int(M['m10']/M['m00'])
                cy = int(M['m01']/M['m00'])

                #combine psx,psy coords with centroid coords from above
                cx += psx
                cy += psy

                #print("Area:",cv2.contourArea(con))
                #print(con[0][0][0],con[0][0][1])
                Mouse.moveClick(cx,cy, 1)
                return cx,cy
            else:
                continue
项目: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 pink objects in the image
      lower_pink = numpy.array([139, 0, 240], numpy.uint8)
      upper_pink = numpy.array([159, 121, 255], numpy.uint8)
      mask = cv2.inRange(hsv, lower_pink, upper_pink)

      # 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 target found
      if self.contourLength < 1:
         print "No target found"

      else:                       # target found

         ## 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])

         #### Target #### the largest "pink" object
         target_image = contours[area.index(max(area))]

         # Using moments find the center of the object and draw a red outline around the object
         target_m = cv2.moments(target_image)
         self.target_u = int(target_m['m10']/target_m['m00'])
         self.target_v = int(target_m['m01']/target_m['m00'])
         points = cv2.minAreaRect(target_image)
         box = cv2.cv.BoxPoints(points)
         box = numpy.int0(box)
         cv2.drawContours(image, [box], 0, (0, 0, 255), 2)
         rospy.loginfo("Center of target is x at %d and y at %d", int(self.target_u), int(self.target_v))

         self.target_found = True               # set flag for depth_callback processing

         # show image with target outlined with a red rectangle
         cv2.imshow ("Target", 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 pink target.
项目: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.
项目:indices    作者:shekharshank    | 项目源码 | 文件源码
def detect_barcode(imageval):


    # load the image and convert it to grayscale

    file_bytes = np.asarray(bytearray(imageval), dtype=np.uint8)
        img_data_ndarray = cv2.imdecode(file_bytes, cv2.CV_LOAD_IMAGE_UNCHANGED)
    gray = cv2.cvtColor(img_data_ndarray, cv2.COLOR_BGR2GRAY)

    # compute the Scharr gradient magnitude representation of the images
    # in both the x and y direction
    gradX = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 1, dy = 0, ksize = -1)
    gradY = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 0, dy = 1, ksize = -1)

    # subtract the y-gradient from the x-gradient
    gradient = cv2.subtract(gradX, gradY)
    gradient = cv2.convertScaleAbs(gradient)

    # blur and threshold the image
    blurred = cv2.blur(gradient, (9, 9))
    (_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)

    # construct a closing kernel and apply it to the thresholded image
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
    closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

    # perform a series of erosions and dilations
    closed = cv2.erode(closed, None, iterations = 4)
    closed = cv2.dilate(closed, None, iterations = 4)

    # find the contours in the thresholded image, then sort the contours
    # by their area, keeping only the largest one
    (cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
    c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]

    # compute the rotated bounding box of the largest contour
    rect = cv2.minAreaRect(c)
    box = np.int0(cv2.cv.BoxPoints(rect))

    # draw a bounding box arounded the detected barcode and display the
    # image
    cv2.drawContours(img_data_ndarray, [box], -1, (0, 255, 0), 3)
    # cv2.imshow("Image", image)
    #cv2.imwrite("uploads/output-"+ datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S")  +".jpg",image)
    # cv2.waitKey(0)

    #outputfile = "uploads/output-" + time.strftime("%H:%M:%S") + ".jpg"
    outputfile = "uploads/output.jpg"

    cv2.imwrite(outputfile,img_data_ndarray)