Python cv2.CC_STAT_AREA Examples

The following are 4 code examples of cv2.CC_STAT_AREA(). 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: craft_utils.py    From CRAFT-pytorch with MIT License 4 votes vote down vote up
def getDetBoxes_core(textmap, linkmap, text_threshold, link_threshold, low_text):
    # prepare data
    linkmap = linkmap.copy()
    textmap = textmap.copy()
    img_h, img_w = textmap.shape

    """ labeling method """
    ret, text_score = cv2.threshold(textmap, low_text, 1, 0)
    ret, link_score = cv2.threshold(linkmap, link_threshold, 1, 0)

    text_score_comb = np.clip(text_score + link_score, 0, 1)
    nLabels, labels, stats, centroids = cv2.connectedComponentsWithStats(text_score_comb.astype(np.uint8), connectivity=4)

    det = []
    mapper = []
    for k in range(1,nLabels):
        # size filtering
        size = stats[k, cv2.CC_STAT_AREA]
        if size < 10: continue

        # thresholding
        if np.max(textmap[labels==k]) < text_threshold: continue

        # make segmentation map
        segmap = np.zeros(textmap.shape, dtype=np.uint8)
        segmap[labels==k] = 255
        segmap[np.logical_and(link_score==1, text_score==0)] = 0   # remove link area
        x, y = stats[k, cv2.CC_STAT_LEFT], stats[k, cv2.CC_STAT_TOP]
        w, h = stats[k, cv2.CC_STAT_WIDTH], stats[k, cv2.CC_STAT_HEIGHT]
        niter = int(math.sqrt(size * min(w, h) / (w * h)) * 2)
        sx, ex, sy, ey = x - niter, x + w + niter + 1, y - niter, y + h + niter + 1
        # boundary check
        if sx < 0 : sx = 0
        if sy < 0 : sy = 0
        if ex >= img_w: ex = img_w
        if ey >= img_h: ey = img_h
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(1 + niter, 1 + niter))
        segmap[sy:ey, sx:ex] = cv2.dilate(segmap[sy:ey, sx:ex], kernel)

        # make box
        np_contours = np.roll(np.array(np.where(segmap!=0)),1,axis=0).transpose().reshape(-1,2)
        rectangle = cv2.minAreaRect(np_contours)
        box = cv2.boxPoints(rectangle)

        # align diamond-shape
        w, h = np.linalg.norm(box[0] - box[1]), np.linalg.norm(box[1] - box[2])
        box_ratio = max(w, h) / (min(w, h) + 1e-5)
        if abs(1 - box_ratio) <= 0.1:
            l, r = min(np_contours[:,0]), max(np_contours[:,0])
            t, b = min(np_contours[:,1]), max(np_contours[:,1])
            box = np.array([[l, t], [r, t], [r, b], [l, b]], dtype=np.float32)

        # make clock-wise order
        startidx = box.sum(axis=1).argmin()
        box = np.roll(box, 4-startidx, 0)
        box = np.array(box)

        det.append(box)
        mapper.append(k)

    return det, labels, mapper 
Example #2
Source File: image_resize.py    From kaggle-dsb2018 with Apache License 2.0 4 votes vote down vote up
def get_mean_cell_size(mask_contours):
    nuclei_sizes = []
    for mask_contour in mask_contours: 
        mask = mask_contour[:,:,0]
        contour = mask_contour[:,:,1]
        new_mask = (mask*255).astype(np.uint8)
        new_contour = (contour*255).astype(np.uint8)
        true_foreground = cv2.subtract(new_mask, new_contour)
        output = cv2.connectedComponentsWithStats(true_foreground)
        nuclei_sizes.append(np.mean(output[2][1:,cv2.CC_STAT_AREA]))
    return nuclei_sizes 
Example #3
Source File: abstract_net.py    From bonnet with GNU General Public License v3.0 3 votes vote down vote up
def obj_histogram(self, mask, label):
    # holders for predicted object and right object (easily calculate histogram)
    predicted = []
    labeled = []

    # get connected components in label for each class
    for i in range(self.num_classes):
      # get binary image for this class
      bin_lbl = np.zeros(label.shape)
      bin_lbl[label == i] = 1
      bin_lbl[label != i] = 0

      # util.im_gray_plt(bin_lbl,'class '+str(i))
      connectivity = 4
      output = cv2.connectedComponentsWithStats(
          bin_lbl.astype(np.uint8), connectivity, cv2.CV_32S)
      num_components = output[0]
      components = output[1]
      stats = output[2]
      centroids = output[3]

      for j in range(1, num_components):  # 0 is background (useless)
        # only process if it has more than 50pix
        if stats[j][cv2.CC_STAT_AREA] > 50:
          # for each component in each class, see the class with the highest percentage of pixels
          # make mask with just this component of this class
          comp_mask = np.zeros(label.shape)
          comp_mask[components == j] = 0
          comp_mask[components != j] = 1
          # mask the prediction
          masked_prediction = np.ma.masked_array(mask, mask=comp_mask)
          # get histogram and get the argmax that is not zero
          class_hist, _ = np.histogram(masked_prediction.compressed(),
                                       bins=self.num_classes, range=[0, self.num_classes])
          max_class = np.argmax(class_hist)
          # print("\nMax class: ",max_class,"  real: ",i)
          # util.im_gray_plt(comp_mask)
          # util.im_block()
          # sum an entry to the containers depending on right or wrong
          predicted.append(max_class)
          labeled.append(i)
    # for idx in range(len(predicted)):
    #   print(predicted[idx],labeled[idx])

    # histogram to count right and wrong objects
    histrange = np.array([[-0.5, self.num_classes - 0.5],
                          [-0.5, self.num_classes - 0.5]], dtype='float64')
    h_now, _, _ = np.histogram2d(np.array(predicted),
                                 np.array(labeled),
                                 bins=self.num_classes,
                                 range=histrange)

    return h_now 
Example #4
Source File: image_processing.py    From kaggle-dsb2018 with Apache License 2.0 3 votes vote down vote up
def post_process_image(image, mask, contour):
    """ Watershed on the markers generated on the sure foreground to find all disconnected objects
    The (mask - contour) is the true foreground. We set the contour to be unknown area. 
    Index of contour = -1
    Index of unkown area = 0
    Index of background = 1  -> set back to 0 after watershed
    Index of found objects > 1
    """
    
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
    
    new_contour = (contour*255).astype(np.uint8)
    new_mask = (mask*255).astype(np.uint8)
    new_mask = cv2.morphologyEx(new_mask, cv2.MORPH_OPEN, kernel, iterations=1)
  

    _, thresh_mask = cv2.threshold(new_mask,0,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    _, thresh_contour = cv2.threshold(new_contour,0,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    sure_background = cv2.dilate(thresh_mask,kernel,iterations=3)
    
    sure_foreground = cv2.subtract(thresh_mask, thresh_contour)
    mask_plus_contour = cv2.add(thresh_mask, thresh_contour)
    mask_plus_contour = cv2.cvtColor(mask_plus_contour, cv2.COLOR_GRAY2RGB)

    unknown = cv2.subtract(sure_background, sure_foreground)
    # Marker labelling
    output = cv2.connectedComponentsWithStats(sure_foreground)
    labels = output[1]
    stats = output[2]
    # Add one to all labels so that sure background is not 0, 0 is considered unknown by watershed
    # this way, watershed can distinguish unknown from the background
    labels = labels + 1
    labels[unknown==255] = 0

    try:
        # random walker on thresh_mask leads a lot higher mean IoU but lower LB
        #labels = random_walker(thresh_mask, labels)   
        # random walker on thresh_mask leads lower mean IoU but higher LB
        labels = random_walker(mask_plus_contour, labels, multichannel=True)   

    except:
        labels = cv2.watershed(mask_plus_contour, labels)

    labels[labels==-1] = 0
    labels[labels==1] = 0
    labels = labels -1
    labels[labels==-1] = 0
    # discard nuclei which are too big or too small
    mean = np.mean(stats[1:,cv2.CC_STAT_AREA])

    for i in range(1, labels.max()):
         if stats[i, cv2.CC_STAT_AREA] > mean*10 or stats[i, cv2.CC_STAT_AREA] < mean/10:
            labels[labels==i] = 0
            
    labels = renumber_labels(labels)
        
    return labels