Python cv2.CHAIN_APPROX_NONE Examples

The following are 30 code examples of cv2.CHAIN_APPROX_NONE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: imutils.py    From ATX with Apache License 2.0 7 votes vote down vote up
def diff_rect(img1, img2, pos=None):
    """find counters include pos in differences between img1 & img2 (cv2 images)"""
    diff = cv2.absdiff(img1, img2)
    diff = cv2.GaussianBlur(diff, (3, 3), 0)
    edges = cv2.Canny(diff, 100, 200)
    _, thresh = cv2.threshold(edges, 0, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    if not contours:
        return None
    contours.sort(key=lambda c: len(c))
    # no pos provide, just return the largest different area rect
    if pos is None:
        cnt = contours[-1]
        x0, y0, w, h = cv2.boundingRect(cnt)
        x1, y1 = x0+w, y0+h
        return (x0, y0, x1, y1)
    # else the rect should contain the pos
    x, y = pos
    for i in range(len(contours)):
        cnt = contours[-1-i]
        x0, y0, w, h = cv2.boundingRect(cnt)
        x1, y1 = x0+w, y0+h
        if x0 <= x <= x1 and y0 <= y <= y1:
            return (x0, y0, x1, y1) 
Example #2
Source File: transforms_rbbox.py    From AerialDetection with Apache License 2.0 7 votes vote down vote up
def mask2poly_single(binary_mask):
    """

    :param binary_mask:
    :return:
    """
    try:
        contours, hierarchy = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        # contour_lens = np.array(list(map(len, contours)))
        # max_id = contour_lens.argmax()
        # max_contour = contours[max_id]
        max_contour = max(contours, key=len)
        rect = cv2.minAreaRect(max_contour)
        poly = cv2.boxPoints(rect)
        # poly = TuplePoly2Poly(poly)
    except:
        import pdb
        pdb.set_trace()
    return poly 
Example #3
Source File: vis.py    From Parsing-R-CNN with MIT License 7 votes vote down vote up
def vis_mask(img, mask, bbox_color, show_parss=False):
    """Visualizes a single binary mask."""
    img = img.astype(np.float32)
    idx = np.nonzero(mask)

    border_color = cfg.VIS.SHOW_SEGMS.BORDER_COLOR
    border_thick = cfg.VIS.SHOW_SEGMS.BORDER_THICK

    mask_color = bbox_color if cfg.VIS.SHOW_SEGMS.MASK_COLOR_FOLLOW_BOX else _WHITE
    mask_color = np.asarray(mask_color)
    mask_alpha = cfg.VIS.SHOW_SEGMS.MASK_ALPHA

    _, contours, _ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
    if cfg.VIS.SHOW_SEGMS.SHOW_BORDER:
        cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA)

    if cfg.VIS.SHOW_SEGMS.SHOW_MASK and not show_parss:
        img[idx[0], idx[1], :] *= 1.0 - mask_alpha
        img[idx[0], idx[1], :] += mask_alpha * mask_color

    return img.astype(np.uint8) 
Example #4
Source File: vis.py    From Parsing-R-CNN with MIT License 7 votes vote down vote up
def vis_parsing(img, parsing, colormap, show_segms=True):
    """Visualizes a single binary parsing."""
    img = img.astype(np.float32)
    idx = np.nonzero(parsing)

    parsing_alpha = cfg.VIS.SHOW_PARSS.PARSING_ALPHA
    colormap = colormap_utils.dict2array(colormap)
    parsing_color = colormap[parsing.astype(np.int)]

    border_color = cfg.VIS.SHOW_PARSS.BORDER_COLOR
    border_thick = cfg.VIS.SHOW_PARSS.BORDER_THICK

    img[idx[0], idx[1], :] *= 1.0 - parsing_alpha
    # img[idx[0], idx[1], :] += alpha * parsing_color
    img += parsing_alpha * parsing_color

    if cfg.VIS.SHOW_PARSS.SHOW_BORDER and not show_segms:
        _, contours, _ = cv2.findContours(parsing.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
        cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA)

    return img.astype(np.uint8) 
Example #5
Source File: coco_seg_fast.py    From PolarMask with Apache License 2.0 7 votes vote down vote up
def get_single_centerpoint(self, mask):
        contour, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        contour.sort(key=lambda x: cv2.contourArea(x), reverse=True)  # only save the biggest one

        '''debug IndexError: list index out of range'''
        count = contour[0][:, 0, :]
        try:
            center = self.get_centerpoint(count)
        except:
            x,y = count.mean(axis=0)
            center=[int(x), int(y)]
            
        #decrease the number of contour, to speed up
        # 360 points should ok, the performance drop very tiny.
        max_points = 360
        if len(contour[0]) > max_points:
            compress_rate = len(contour[0]) // max_points
            contour[0] = contour[0][::compress_rate, ...]
        return center, contour 
Example #6
Source File: getBlobTrajectories.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def _remove_corner_blobs(ROI_image):
    #remove blobs specially in the corners that could be part of other ROI
    # get the border of the ROI mask, this will be used to filter for valid
    # worms
    ROI_valid = (ROI_image != 0).astype(np.uint8)

    ROI_border_ind, _ = cv2.findContours(ROI_valid, 
                                            cv2.RETR_EXTERNAL, 
                                            cv2.CHAIN_APPROX_NONE)[-2:]


    if len(ROI_border_ind) > 1:
        # consider the case where there is more than one contour in the blob
        # i.e. there is a neighboring ROI in the square, just keep the largest area
        ROI_area = [cv2.contourArea(x) for x in ROI_border_ind]
        valid_ind = np.argmax(ROI_area)
        ROI_valid = np.zeros_like(ROI_valid)
        ROI_valid = cv2.drawContours(ROI_valid, ROI_border_ind, valid_ind, 1, -1)
        ROI_image = ROI_image * ROI_valid

    return ROI_image 
Example #7
Source File: Dataloader.py    From Text_Segmentation_Image_Inpainting with GNU General Public License v3.0 6 votes vote down vote up
def draw_contour(img, mask):
    a, b, c = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    for cnt in b:
        approx = cv2.approxPolyDP(cnt, 0, True)
        cv2.drawContours(img, [approx], 0, (255, 255, 255), -1)
    return img 
Example #8
Source File: plate_locate.py    From EasyPR-python with Apache License 2.0 6 votes vote down vote up
def sobelSecSearchPart(self, bound, refpoint, out):
        bound_threshold = self.sobelOperT(bound, 3, 6, 2)

        tempBoundThread = bound_threshold.copy()
        clearLiuDingOnly(tempBoundThread)

        posLeft, posRight, flag = bFindLeftRightBound(tempBoundThread)
        if flag:
            if posRight != 0 and posLeft != 0 and posLeft < posRight:
                posY = int(bound_threshold.shape[0] * 0.5)
                for i in range(posLeft + int(bound_threshold.shape[0] * 0.1), posRight - 4):
                    bound_threshold[posY, i] = 255
            for i in range(bound_threshold.shape[0]):
                bound_threshold[i, posLeft] = 0
                bound_threshold[i, posRight] = 0

        _, contours, _ = cv2.findContours(bound_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        for it in contours:
            mr = cv2.minAreaRect(it)
            if self.verifySizes(mr):
                tmp = (mr[0][0] + refpoint[0], mr[0][1] + refpoint[1])
                out.append((tmp, mr[1], mr[2])) 
Example #9
Source File: plate_locate.py    From EasyPR-python with Apache License 2.0 6 votes vote down vote up
def sobelFrtSearch(self, src):
        out_rects = []

        src_threshold = self.sobelOper(src, self.m_GaussianBlurSize, self.m_MorphSizeWidth, self.m_MorphSizeHeight)
        _, contours, _ = cv2.findContours(src_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

        for it in contours:
            mr = cv2.minAreaRect(it)

            if self.verifySizes(mr):
                safeBoundRect, flag = self.calcSafeRect(mr, src)
                if not flag:
                    continue
                out_rects.append(safeBoundRect)

        return out_rects 
Example #10
Source File: plate_locate.py    From EasyPR-python with Apache License 2.0 6 votes vote down vote up
def colorSearch(self, src, color, out_rect):
        """

        :param src:
        :param color:
        :param out_rect: minAreaRect
        :return: binary
        """
        color_morph_width = 10
        color_morph_height = 2

        match_gray = colorMatch(src, color, False)

        _, src_threshold = cv2.threshold(match_gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

        element = cv2.getStructuringElement(cv2.MORPH_RECT, (color_morph_width, color_morph_height))
        src_threshold = cv2.morphologyEx(src_threshold, cv2.MORPH_CLOSE, element)

        out = src_threshold.copy()

        _, contours, _ = cv2.findContours(src_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

        for cnt in contours:
            mr = cv2.minAreaRect(cnt)
            if self.verifySizes(mr):
                out_rect.append(mr)

        return out 
Example #11
Source File: coco_seg.py    From PolarMask with Apache License 2.0 6 votes vote down vote up
def get_single_centerpoint(self, mask):
        contour, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        contour.sort(key=lambda x: cv2.contourArea(x), reverse=True) #only save the biggest one
        '''debug IndexError: list index out of range'''
        count = contour[0][:, 0, :]
        try:
            center = self.get_centerpoint(count)
        except:
            x,y = count.mean(axis=0)
            center=[int(x), int(y)]

        # max_points = 360
        # if len(contour[0]) > max_points:
        #     compress_rate = len(contour[0]) // max_points
        #     contour[0] = contour[0][::compress_rate, ...]
        return center, contour 
Example #12
Source File: visualize.py    From ExtremeNet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=2):
    """Visualizes a single binary mask."""

    img = img.astype(np.float32)
    idx = np.nonzero(mask)

    img[idx[0], idx[1], :] *= 1.0 - alpha
    img[idx[0], idx[1], :] += alpha * col

    if show_border:
        # How to use `cv2.findContours` in different OpenCV versions?
        # https://stackoverflow.com/questions/48291581/how-to-use-cv2-findcontours-in-different-opencv-versions/48292371#48292371
        contours = cv2.findContours(
            mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)[-2]
        cv2.drawContours(img, contours, -1, _WHITE, border_thick, cv2.LINE_AA)

    return img.astype(np.uint8) 
Example #13
Source File: siam_mask_tracker.py    From models with MIT License 6 votes vote down vote up
def _mask_post_processing(mask, center_pos, size, track_mask_threshold):
    target_mask = (mask > track_mask_threshold)
    target_mask = target_mask.astype(np.uint8)
    if cv2.__version__[-5] == '4':
        contours, _ = cv2.findContours(target_mask,
                                       cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_NONE)
    else:
        _, contours, _ = cv2.findContours(
                target_mask,
                cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    cnt_area = [cv2.contourArea(cnt) for cnt in contours]
    if len(contours) != 0 and np.max(cnt_area) > 100:
        contour = contours[np.argmax(cnt_area)] 
        polygon = contour.reshape(-1, 2)
        prbox = cv2.boxPoints(cv2.minAreaRect(polygon))
        rbox_in_img = prbox
    else:  # empty mask
        location = cxy_wh_2_rect(center_pos, size)
        rbox_in_img = np.array([[location[0], location[1]],
                    [location[0] + location[2], location[1]],
                    [location[0] + location[2], location[1] + location[3]],
                    [location[0], location[1] + location[3]]])
    return rbox_in_img 
Example #14
Source File: locate_tissue.py    From tissueloc with MIT License 6 votes vote down vote up
def find_tissue_cnts(bw_img):
    """ Fint contours of tissues
    Parameters
    ----------
    bw_img : np.array
        2D binary image.
    Returns
    -------
    cnts: list
        List of all contours coordinates of tissues.
    """

    cnts, _ = cv2.findContours(img_as_ubyte(bw_img), mode=cv2.RETR_EXTERNAL,
                               method=cv2.CHAIN_APPROX_NONE)

    return cnts 
Example #15
Source File: markers.py    From Zozo-Measurer with GNU General Public License v3.0 6 votes vote down vote up
def find_marker_ellipses(im):
    im_gray = cvtColor(im, COLOR_BGR2GRAY)
    im_blur = GaussianBlur(im_gray, (3, 3), 0)
    ret, th = threshold(im_blur, 0, 255, THRESH_BINARY_INV + THRESH_OTSU)
    imgEdge, contours, hierarchy = findContours(th, RETR_TREE, CHAIN_APPROX_NONE)
    points = []
    origins = []
    ellipses = []
    id_point_candidates = []
    small_point_candidates = []
    for cnt in contours:
        if contour_sanity_check(cnt, im.shape[0], point_d=0.02):
            id_point_candidates.append(cnt)
        elif contour_sanity_check(cnt, im.shape[0], point_d=0.01):
            small_point_candidates.append(cnt)
    for cnt in id_point_candidates:
        x, y, w, h = boundingRect(cnt)
        ellipse = fitEllipse(cnt)
        points.append(im_gray[y:y + h, x:x + w])
        origins.append((x, y))
        ellipses.append(ellipse)
    return points, origins, ellipses 
Example #16
Source File: siammask_tracker.py    From pysot with Apache License 2.0 6 votes vote down vote up
def _mask_post_processing(self, mask):
        target_mask = (mask > cfg.TRACK.MASK_THERSHOLD)
        target_mask = target_mask.astype(np.uint8)
        if cv2.__version__[-5] == '4':
            contours, _ = cv2.findContours(target_mask,
                                           cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)
        else:
            _, contours, _ = cv2.findContours(target_mask,
                                              cv2.RETR_EXTERNAL,
                                              cv2.CHAIN_APPROX_NONE)
        cnt_area = [cv2.contourArea(cnt) for cnt in contours]
        if len(contours) != 0 and np.max(cnt_area) > 100:
            contour = contours[np.argmax(cnt_area)]
            polygon = contour.reshape(-1, 2)
            prbox = cv2.boxPoints(cv2.minAreaRect(polygon))
            rbox_in_img = prbox
        else:  # empty mask
            location = cxy_wh_2_rect(self.center_pos, self.size)
            rbox_in_img = np.array([[location[0], location[1]],
                                    [location[0] + location[2], location[1]],
                                    [location[0] + location[2], location[1] + location[3]],
                                    [location[0], location[1] + location[3]]])
        return rbox_in_img 
Example #17
Source File: class_PlateDetection.py    From ALPR_System with Apache License 2.0 6 votes vote down vote up
def clean_plate(self, plate):
        gray = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY)
        thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
        _, contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

        if contours:
            areas = [cv2.contourArea(c) for c in contours]
            max_index = np.argmax(areas) # index of the largest contour in the area array
            
            max_cnt = contours[max_index]
            max_cntArea = areas[max_index]
            x,y,w,h = cv2.boundingRect(max_cnt)
            rect = cv2.minAreaRect(max_cnt)
            rotatedPlate = self.crop_rotated_contour(plate, rect)
            if not self.ratioCheck(max_cntArea, rotatedPlate.shape[1], rotatedPlate.shape[0]):
                return plate, False, None
            return rotatedPlate, True, [x, y, w, h]
        else:
            return plate, False, None 
Example #18
Source File: getBlobTrajectories.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def getBlobsSimple(in_data, blob_params):
    frame_number, image = in_data
    min_area, worm_bw_thresh_factor, strel_size = blob_params
    
    
    img_m = cv2.medianBlur(image, 3)
    
    valid_pix = img_m[img_m>0]
    if len(valid_pix) == 0:
        return []
    
    th = _thresh_bw(valid_pix)*worm_bw_thresh_factor
    
    _, bw = cv2.threshold(img_m, th,255,cv2.THRESH_BINARY)
    if np.all(strel_size):
        strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, strel_size)
        bw = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, strel)

    cnts, hierarchy = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
    
    
    blobs_data = _cnt_to_props(cnts, frame_number, th, min_area)
    return blobs_data 
Example #19
Source File: zebrafishAnalysis.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def getHeadMask(frame):

    th_val = 1

    ret, img_thresh = cv2.threshold(frame, th_val, 255, cv2.THRESH_BINARY)

    # Remove excess noise by drawing only the largest contour

    head_mask = np.zeros((img_thresh.shape[0], img_thresh.shape[1]), np.uint8)


    contours, hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
    contours.sort(key=lambda ar: ar.size)
    head_contour = contours[-1]


    cv2.drawContours(head_mask, [head_contour], 0, 255, cv2.FILLED)

    return head_mask 
Example #20
Source File: getBlobTrajectories.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def getBlobContours(ROI_image, 
                    thresh, 
                    strel_size=(5, 5), 
                    is_light_background=True, 
                    analysis_type="WORM", 
                    thresh_block_size=15):

    
    ROI_image = _remove_corner_blobs(ROI_image)
    ROI_mask, thresh = _get_blob_mask(ROI_image, thresh, thresh_block_size, is_light_background, analysis_type)
    
    # clean it using morphological closing - make this optional by setting strel_size to 0
    if np.all(strel_size):
        strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, strel_size)
        ROI_mask = cv2.morphologyEx(ROI_mask, cv2.MORPH_CLOSE, strel)

    # get worms, assuming each contour in the ROI is a worm

    ROI_worms, hierarchy = cv2.findContours(ROI_mask, 
                                               cv2.RETR_EXTERNAL, 
                                               cv2.CHAIN_APPROX_NONE)[-2:]


    return ROI_worms, hierarchy 
Example #21
Source File: viz.py    From Object_Detection_Tracking with Apache License 2.0 6 votes vote down vote up
def draw_mask(im, mask, alpha=0.5, color=None, show_border=True,border_thick=1):
	"""
	Overlay a mask on top of the image.

	Args:
		im: a 3-channel uint8 image in BGR
		mask: a binary 1-channel image of the same size
		color: if None, will choose automatically
	"""
	if color is None:
		color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]


	im = np.where(np.squeeze(np.repeat((mask > 0)[:, :, None], 3, axis=2)),
				  im * (1 - alpha) + color * alpha, im)
	if show_border:
		if cv2.__version__.startswith("2"):
			contours, _ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
		else: # cv 3
			_,contours, _ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
		cv2.drawContours(im, contours, -1, (255,255,255), border_thick, lineType=cv2.CV_AA)

	im = im.astype('uint8')
	return im 
Example #22
Source File: TextDetect.py    From text-detection with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def text_detect(img,ele_size=(8,2)): #
    if len(img.shape)==3:
        img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    img_sobel = cv2.Sobel(img,cv2.CV_8U,1,0)#same as default,None,3,1,0,cv2.BORDER_DEFAULT)
    img_threshold = cv2.threshold(img_sobel,0,255,cv2.THRESH_OTSU+cv2.THRESH_BINARY)
    element = cv2.getStructuringElement(cv2.MORPH_RECT,ele_size)
    img_threshold = cv2.morphologyEx(img_threshold[1],cv2.MORPH_CLOSE,element)
    res = cv2.findContours(img_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    if cv2.__version__.split(".")[0] == '3':
        _, contours, hierarchy = res
    else:
        contours, hierarchy = res
    Rect = [cv2.boundingRect(i) for i in contours if i.shape[0]>100]
    RectP = [(int(i[0]-i[2]*0.08),int(i[1]-i[3]*0.08),int(i[0]+i[2]*1.1),int(i[1]+i[3]*1.1)) for i in Rect]
    return RectP 
Example #23
Source File: vis.py    From Clustered-Object-Detection-in-Aerial-Image with Apache License 2.0 5 votes vote down vote up
def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=1):
    """Visualizes a single binary mask."""

    img = img.astype(np.float32)
    idx = np.nonzero(mask)

    img[idx[0], idx[1], :] *= 1.0 - alpha
    img[idx[0], idx[1], :] += alpha * col

    if show_border:
        _, contours, _ = cv2.findContours(
            mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
        cv2.drawContours(img, contours, -1, _WHITE, border_thick, cv2.LINE_AA)

    return img.astype(np.uint8) 
Example #24
Source File: vis.py    From CBNet with Apache License 2.0 5 votes vote down vote up
def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=1):
    """Visualizes a single binary mask."""

    img = img.astype(np.float32)
    idx = np.nonzero(mask)

    img[idx[0], idx[1], :] *= 1.0 - alpha
    img[idx[0], idx[1], :] += alpha * col

    if show_border:
        _, contours, _ = cv2.findContours(
            mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
        cv2.drawContours(img, contours, -1, _WHITE, border_thick, cv2.LINE_AA)

    return img.astype(np.uint8) 
Example #25
Source File: preparation.py    From open-solution-data-science-bowl-2018 with MIT License 5 votes vote down vote up
def get_contour(img):
    img_contour = np.zeros_like(img).astype(np.uint8)
    _, contours, hierarchy = cv2.findContours(img.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    cv2.drawContours(img_contour, contours, -1, (255, 255, 255), 4)
    return img_contour 
Example #26
Source File: postprocessing.py    From open-solution-mapping-challenge with MIT License 5 votes vote down vote up
def get_contour(mask):
    mask_contour = np.zeros_like(mask).astype(np.uint8)
    _, contours, hierarchy = cv2.findContours(mask.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    cv2.drawContours(mask_contour, contours, -1, (255, 255, 255), 1)
    return mask_contour 
Example #27
Source File: class_PlateDetection.py    From ALPR_System with Apache License 2.0 5 votes vote down vote up
def extract_contours(self, after_preprocess):
        _, extracted_contours, _ = cv2.findContours(after_preprocess, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
        return extracted_contours 
Example #28
Source File: vis.py    From Parsing-R-CNN with MIT License 5 votes vote down vote up
def vis_uv_temp(img, uv, bbox, show_segms=True):
    """Visualizes a single binary parsing."""
    padded_uv = np.zeros((img.shape), dtype=np.float32)
    uv_temp = np.array([uv[0], uv[1] * 256, uv[2] * 256]).transpose(1, 2, 0)
    y2 = int(bbox[1]) + int(bbox[3] - bbox[1])
    x2 = int(bbox[0]) + int(bbox[2] - bbox[0])
    padded_uv[int(bbox[1]):y2, int(bbox[0]):x2] = uv_temp

    img = img.astype(np.float32)
    idx = np.nonzero(padded_uv[:, :, 0])

    uv_alpha = cfg.VIS.SHOW_UV.UV_ALPHA

    border_color = cfg.VIS.SHOW_UV.BORDER_COLOR
    border_thick = cfg.VIS.SHOW_UV.BORDER_THICK

    img[idx[0], idx[1], :] *= 1.0 - uv_alpha
    img += uv_alpha * padded_uv

    if cfg.VIS.SHOW_UV.SHOW_BORDER and not show_segms:
        _, contours, _ = cv2.findContours(
            padded_uv[:, :, 0].astype(np.uint8).copy(),
            cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE
        )
        cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA)

    return img.astype(np.uint8) 
Example #29
Source File: vis.py    From Detectron-Cascade-RCNN with Apache License 2.0 5 votes vote down vote up
def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=1):
    """Visualizes a single binary mask."""

    img = img.astype(np.float32)
    idx = np.nonzero(mask)

    img[idx[0], idx[1], :] *= 1.0 - alpha
    img[idx[0], idx[1], :] += alpha * col

    if show_border:
        _, contours, _ = cv2.findContours(
            mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
        cv2.drawContours(img, contours, -1, _WHITE, border_thick, cv2.LINE_AA)

    return img.astype(np.uint8) 
Example #30
Source File: visualizer.py    From detectron2 with Apache License 2.0 5 votes vote down vote up
def mask_to_polygons(self, mask):
        # cv2.RETR_CCOMP flag retrieves all the contours and arranges them to a 2-level
        # hierarchy. External contours (boundary) of the object are placed in hierarchy-1.
        # Internal contours (holes) are placed in hierarchy-2.
        # cv2.CHAIN_APPROX_NONE flag gets vertices of polygons from contours.
        mask = np.ascontiguousarray(mask)  # some versions of cv2 does not support incontiguous arr
        res = cv2.findContours(mask.astype("uint8"), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
        hierarchy = res[-1]
        if hierarchy is None:  # empty mask
            return [], False
        has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0
        res = res[-2]
        res = [x.flatten() for x in res]
        res = [x for x in res if len(x) >= 6]
        return res, has_holes