Python skimage.draw.polygon() Examples

The following are 30 code examples of skimage.draw.polygon(). 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 skimage.draw , or try the search function .
Example #1
Source File: geometry.py    From phidl with MIT License 6 votes vote down vote up
def straight(size = (4,2), layer = 0):
    """Generates a rectangular wire geometry with ports on the length edges.

    Parameters
    ----------
    size : tuple
        The length and width of the rectangle.
    layer : int, array-like[2], or set
        Specific layer(s) to put polygon geometry on.

    Returns
    -------
    A Device with an rectangle polygon in it, and two ports (`1` and `2`) on either end

    Notes
    -----
    Ports are included on both sides of the length edge (i.e. size[0]) of the geometry.
    """

    D = Device(name = 'wire')
    points = [[size[0], size[1]], [size[0], 0], [0, 0], [0, size[1]]]
    D.add_polygon(points, layer = layer)
    D.add_port(name = 1, midpoint = (size[0]/2, size[1]),  width = size[0], orientation = 90)
    D.add_port(name = 2, midpoint = (size[0]/2, 0),  width = size[0], orientation = -90)
    return D 
Example #2
Source File: dataset.py    From calamari with Apache License 2.0 6 votes vote down vote up
def cutout(pageimg, coordstring, scale=1, rect=False):
        coords = [p.split(",") for p in coordstring.split()]
        coords = np.array([(int(scale * int(c[1])), int(scale * int(c[0])))
                           for c in coords])
        if rect:
            return pageimg[min(c[0] for c in coords):max(c[0] for c in coords),
                   min(c[1] for c in coords):max(c[1] for c in coords)]
        rr, cc = polygon(coords[:, 0], coords[:, 1], pageimg.shape)
        offset = (min([x[0] for x in coords]), min([x[1] for x in coords]))
        box = np.ones(
            (max([x[0] for x in coords]) - offset[0],
             max([x[1] for x in coords]) - offset[1],
             ) + ((pageimg.shape[-1],) if len(pageimg.shape) == 3 else ()),
            dtype=pageimg.dtype) * 255
        box[rr - offset[0], cc - offset[1]] = pageimg[rr, cc]
        return box 
Example #3
Source File: coco.py    From kaggle-rsna18 with MIT License 6 votes vote down vote up
def annToRLE(self, ann):
        """
        Convert annotation which can be polygons, uncompressed RLE to RLE.
        :return: binary mask (numpy 2D array)
        """
        t = self.imgs[ann['image_id']]
        h, w = t['height'], t['width']
        segm = ann['segmentation']
        if type(segm) == list:
            # polygon -- a single object might consist of multiple parts
            # we merge all parts into one mask rle code
            rles = mask.frPyObjects(segm, h, w)
            rle = mask.merge(rles)
        elif type(segm['counts']) == list:
            # uncompressed RLE
            rle = mask.frPyObjects(segm, h, w)
        else:
            # rle
            rle = ann['segmentation']
        return rle 
Example #4
Source File: segmentation.py    From kraken with Apache License 2.0 6 votes vote down vote up
def scale_regions(regions: Sequence[Tuple[List, List]],
                  scale: Union[float, Tuple[float, float]]) -> Sequence[Tuple[List, List]]:
    """
    Scales baselines/polygon coordinates by a certain factor.

    Args:
        lines (Sequence): List of tuples containing the baseline and it's
                          polygonization.
        scale (float or tuple of floats): Scaling factor
    """
    if isinstance(scale, float):
        scale = (scale, scale)
    scaled_regions = []
    for region in regions:
        scaled_regions.append((np.array(region) * scale).astype('uint').tolist())
    return scaled_regions 
Example #5
Source File: segmentation.py    From kraken with Apache License 2.0 6 votes vote down vote up
def scale_polygonal_lines(lines: Sequence[Tuple[List, List]], scale: Union[float, Tuple[float, float]]) -> Sequence[Tuple[List, List]]:
    """
    Scales baselines/polygon coordinates by a certain factor.

    Args:
        lines (Sequence): List of tuples containing the baseline and it's
                          polygonization.
        scale (float or tuple of floats): Scaling factor
    """
    if isinstance(scale, float):
        scale = (scale, scale)
    scaled_lines = []
    for line in lines:
        bl, pl = line
        scaled_lines.append(((np.array(bl) * scale).astype('int').tolist(),
                             (np.array(pl) * scale).astype('int').tolist()))
    return scaled_lines 
Example #6
Source File: segmentation.py    From kraken with Apache License 2.0 6 votes vote down vote up
def _test_intersect(bp, uv, bs):
    """
    Returns the intersection points of a ray with direction `uv` from
    `bp` with a polygon `bs`.
    """
    u = bp - np.roll(bs, 2)
    v = bs - np.roll(bs, 2)
    points = []
    for dir in ((1,-1), (-1,1)):
        w = (uv * dir * (1,-1))[::-1]
        z = np.dot(v, w)
        t1 = np.cross(v, u) / z
        t2 = np.dot(u, w) / z
        t1 = t1[np.logical_and(t2 >= 0.0, t2 <= 1.0)]
        points.extend(bp + (t1[np.where(t1 >= 0)[0].min()] * (uv * dir)))
    return np.array(points) 
Example #7
Source File: roi_image.py    From torchsupport with MIT License 6 votes vote down vote up
def __init__(self, path, size=(226, 226), transform=lambda x: x):
    self.transform = transform
    with Image.open(path + ".tif") as stack:
      frames = []
      for img in ImageSequence.Iterator(stack):
        frame = torch.tensor(np.array(img).astype(float))
        frames.append(frame.unsqueeze(0))
      self.raw_image = torch.cat(frames, dim=0)
    rois = read_roi_zip(path + ".roi.zip")
    self.rois = [
      torch.tensor(zip(*polygon(
        roi[1]["x"], roi[1]["y"],
        shape=(self.raw_image.size(1),
               self.raw_image.size(2))
      )), dtype=torch.long)
      for roi in rois
    ] 
Example #8
Source File: convert_data.py    From aapm_thoracic_challenge with MIT License 6 votes vote down vote up
def get_labels(contours, shape, slices):
    z = [np.around(s.ImagePositionPatient[2], 1) for s in slices]
    pos_r = slices[0].ImagePositionPatient[1]
    spacing_r = slices[0].PixelSpacing[1]
    pos_c = slices[0].ImagePositionPatient[0]
    spacing_c = slices[0].PixelSpacing[0]
    
    label_map = np.zeros(shape, dtype=np.float32)
    for con in contours:
        num = ROI_ORDER.index(con['name']) + 1
        for c in con['contours']:
            nodes = np.array(c).reshape((-1, 3))
            assert np.amax(np.abs(np.diff(nodes[:, 2]))) == 0
            z_index = z.index(np.around(nodes[0, 2], 1))
            r = (nodes[:, 1] - pos_r) / spacing_r
            c = (nodes[:, 0] - pos_c) / spacing_c
            rr, cc = polygon(r, c)
            label_map[z_index, rr, cc] = num
    
    return label_map 
Example #9
Source File: grasp.py    From mvp_grasp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def iou(self, bb, angle_threshold=np.pi/6):
        if abs(self.angle - bb.angle) % np.pi > angle_threshold:
            return 0

        rr1, cc1 = self.polygon_coords()
        rr2, cc2 = polygon(bb.points[:, 0], bb.points[:, 1])

        try:
            r_max = max(rr1.max(), rr2.max()) + 1
            c_max = max(cc1.max(), cc2.max()) + 1
        except:
            return 0

        canvas = np.zeros((r_max, c_max))
        canvas[rr1, cc1] += 1
        canvas[rr2, cc2] += 1
        union = np.sum(canvas > 0)
        if union == 0:
            return 0
        intersection = np.sum(canvas == 2)
        return intersection/union 
Example #10
Source File: geometry.py    From phidl with MIT License 6 votes vote down vote up
def circle(radius = 10, angle_resolution = 2.5, layer = 0):
    """Generate a circle geometry.

    Parameters
    ----------
    radius : float
        Radius of the circle.
    angle_resolution : float
        Resolution of the curve of the ring (# of degrees per point).
    layer : int, array-like[2], or set
        Specific layer(s) to put polygon geometry on.

    Returns
    -------
    A Device with an circle polygon in it

    """

    D = Device(name = 'circle')
    t = np.linspace(0, 360, int(np.ceil(360/angle_resolution) + 1))*pi/180
    xpts = (radius*cos(t)).tolist()
    ypts = (radius*sin(t)).tolist()
    D.add_polygon(points = (xpts,ypts), layer = layer)
    return D 
Example #11
Source File: coco.py    From RoITransformer_DOTA with MIT License 6 votes vote down vote up
def annToRLE(self, ann):
        """
        Convert annotation which can be polygons, uncompressed RLE to RLE.
        :return: binary mask (numpy 2D array)
        """
        t = self.imgs[ann['image_id']]
        h, w = t['height'], t['width']
        segm = ann['segmentation']
        if type(segm) == list:
            # polygon -- a single object might consist of multiple parts
            # we merge all parts into one mask rle code
            rles = mask.frPyObjects(segm, h, w)
            rle = mask.merge(rles)
        elif type(segm['counts']) == list:
            # uncompressed RLE
            rle = mask.frPyObjects(segm, h, w)
        else:
            # rle
            rle = ann['segmentation']
        return rle 
Example #12
Source File: geometry.py    From phidl with MIT License 6 votes vote down vote up
def cross(length = 10, width = 3, layer = 0):
    """Generates a right-angle cross (+ shape, symmetric) from two
    rectangles of specified length and width.

    Parameters
    ----------
    length : float
        Length of the cross from one end to the other.
    width : float
        Width of the arms of the cross.
    layer : int, array-like[2], or set
        Specific layer(s) to put polygon geometry on.

    Returns
    -------
    A Device with a cross in it
    """

    D = Device(name = 'cross')
    R = rectangle(size = (width, length), layer = layer)
    r1 = D.add_ref(R).rotate(90)
    r2 = D.add_ref(R)
    r1.center = (0,0)
    r2.center = (0,0)
    return D 
Example #13
Source File: geometry.py    From phidl with MIT License 6 votes vote down vote up
def bbox(bbox = [(-1,-1),(3,4)], layer = 0):
    """ Creates a bounding box rectangle from coordinates, to allow
    creation of a rectangle bounding box directly form another shape.

    Parameters
    ----------
    bbox : list of tuples
        Coordinates of the box [(x1,y1),(x2,y2)].
    layer : int, array-like[2], or set
        Specific layer(s) to put polygon geometry on.

    Returns
    -------
    A Device with a single rectangle in it

    Examples
    --------
    >>> D = pg.bbox(anothershape.bbox)
    """

    D = Device(name = 'bbox')
    (a,b),(c,d)  = bbox
    points = ((a,b), (c,b), (c,d), (a,d))
    D.add_polygon(points, layer = layer)
    return D 
Example #14
Source File: geometry.py    From phidl with MIT License 6 votes vote down vote up
def rectangle(size = (4,2), layer = 0):
    """Generate rectangle geometry.

    Parameters
    ----------
    size : tuple
        Width and height of rectangle.
    layer : int, array-like[2], or set
        Specific layer(s) to put polygon geometry on.

    Returns
    -------
    A Device with a single rectangle in it
    """

    D = Device(name = 'rectangle')
    points = [[size[0], size[1]], [size[0], 0], [0, 0], [0, size[1]]]
    D.add_polygon(points, layer = layer)
    return D 
Example #15
Source File: img2_coord_ica.py    From kaggle-airbus-ship-detection-challenge with Apache License 2.0 6 votes vote down vote up
def coord2_img(mean_x, mean_y, length, aspect_ratio, rotate, img_size):

    W2 = np.array([[np.cos(rotate), np.sin(rotate)], [-np.sin(rotate), np.cos(rotate)]])

    height = length
    width = height / aspect_ratio

    c = np.array([[-height/2, -width/2], [height/2, -width/2], [height/2, width/2], [-height/2, width/2]])
    c = (W2 @ c.T).T + np.array([mean_y, mean_x])

    img = np.zeros((img_size, img_size), dtype=np.uint8)
    rr, cc = polygon(c[:, 0], c[:, 1])

    index = (rr >= 0) * (rr < img_size) * (cc >= 0) * (cc < img_size)

    img[rr[index], cc[index]] = 255
    return img 
Example #16
Source File: polygon_wrapper.py    From remote_sensing_object_detection_2019 with MIT License 6 votes vote down vote up
def area_of_intersection(det_x, det_y, gt_x, gt_y):
    """
    This helper calculates the area of intersection.
    """
    if approx_area_of_intersection(det_x, det_y, gt_x, gt_y) > 1: #only proceed if it passes the approximation test
        ymax = np.maximum(np.max(det_y), np.max(gt_y)) + 1
        xmax = np.maximum(np.max(det_x), np.max(gt_x)) + 1
        bin_mask = np.zeros((ymax, xmax))
        det_bin_mask = np.zeros_like(bin_mask)
        gt_bin_mask = np.zeros_like(bin_mask)

        rr, cc = polygon(det_y, det_x)
        det_bin_mask[rr, cc] = 1

        rr, cc = polygon(gt_y, gt_x)
        gt_bin_mask[rr, cc] = 1

        final_bin_mask = det_bin_mask + gt_bin_mask

        inter_map = np.where(final_bin_mask == 2, 1, 0)
        inter = np.sum(inter_map)
        return inter
#        return np.round(inter, 2)
    else:
        return 0 
Example #17
Source File: test_descriptors.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ray_features_polygon(self):
        seg = np.ones((400, 600), dtype=bool)
        x, y = draw.polygon(np.array([50, 170, 300, 250, 150, 150, 50]),
                            np.array([100, 270, 240, 150, 150, 80, 50]),
                            shape=seg.shape)
        seg[x, y] = False

        centres = [(150, 200), (200, 250), (250, 200), (120, 100)]
        for i, point in enumerate(centres):
            ray_dist_raw = compute_ray_features_segm_2d(seg, point,
                                                        angle_step=ANGULAR_STEP)
            ray_dist, shift = shift_ray_features(ray_dist_raw)
            points = reconstruct_ray_features_2d(point, ray_dist, shift)
            p_fig = export_ray_results(seg, point, points, ray_dist_raw, ray_dist,
                                       'polygon-%i.png' % i)
            self.assertTrue(os.path.exists(p_fig)) 
Example #18
Source File: coco.py    From Deep-Feature-Flow-Segmentation with MIT License 6 votes vote down vote up
def annToRLE(self, ann):
        """
        Convert annotation which can be polygons, uncompressed RLE to RLE.
        :return: binary mask (numpy 2D array)
        """
        t = self.imgs[ann['image_id']]
        h, w = t['height'], t['width']
        segm = ann['segmentation']
        if type(segm) == list:
            # polygon -- a single object might consist of multiple parts
            # we merge all parts into one mask rle code
            rles = mask.frPyObjects(segm, h, w)
            rle = mask.merge(rles)
        elif type(segm['counts']) == list:
            # uncompressed RLE
            rle = mask.frPyObjects(segm, h, w)
        else:
            # rle
            rle = ann['segmentation']
        return rle 
Example #19
Source File: mask_coco2voc.py    From Deformable-ConvNets with MIT License 5 votes vote down vote up
def segToMask( S, h, w ):
    """
    Convert polygon segmentation to binary mask.
    :param   S (float array)   : polygon segmentation mask
    :param   h (int)           : target mask height
    :param   w (int)           : target mask width
    :return: M (bool 2D array) : binary mask
    """
    M = np.zeros((h,w), dtype=np.bool)
    for s in S:
        N = len(s)
        rr, cc = polygon(np.array(s[1:N:2]).clip(max=h-1), \
                      np.array(s[0:N:2]).clip(max=w-1)) # (y, x)
        M[rr, cc] = 1
    return M 
Example #20
Source File: mask_coco2voc.py    From RoITransformer_DOTA with MIT License 5 votes vote down vote up
def mask_coco2voc(coco_masks, im_height, im_width):
    voc_masks = np.zeros((len(coco_masks), im_height, im_width))
    for i, ann in enumerate(coco_masks):
        if type(ann) == list:
            # polygon
            m = segToMask(ann, im_height, im_width)
        else:
            # rle
            m = decodeMask(ann)
        voc_masks[i,:,:]=m;
    return voc_masks 
Example #21
Source File: coco.py    From RoITransformer_DOTA with MIT License 5 votes vote down vote up
def segToMask( S, h, w ):
         """
         Convert polygon segmentation to binary mask.
         :param   S (float array)   : polygon segmentation mask
         :param   h (int)           : target mask height
         :param   w (int)           : target mask width
         :return: M (bool 2D array) : binary mask
         """
         M = np.zeros((h,w), dtype=np.bool)
         for s in S:
             N = len(s)
             rr, cc = polygon(np.array(s[1:N:2]).clip(max=h-1), \
                              np.array(s[0:N:2]).clip(max=w-1)) # (y, x)
             M[rr, cc] = 1
         return M 
Example #22
Source File: mask_coco2voc.py    From Deformable-ConvNets with MIT License 5 votes vote down vote up
def mask_coco2voc(coco_masks, im_height, im_width):
    voc_masks = np.zeros((len(coco_masks), im_height, im_width))
    for i, ann in enumerate(coco_masks):
        if type(ann) == list:
            # polygon
            m = segToMask(ann, im_height, im_width)
        else:
            # rle
            m = decodeMask(ann)
        voc_masks[i,:,:]=m;
    return voc_masks 
Example #23
Source File: mask_coco2voc.py    From RoITransformer_DOTA with MIT License 5 votes vote down vote up
def segToMask( S, h, w ):
    """
    Convert polygon segmentation to binary mask.
    :param   S (float array)   : polygon segmentation mask
    :param   h (int)           : target mask height
    :param   w (int)           : target mask width
    :return: M (bool 2D array) : binary mask
    """
    M = np.zeros((h,w), dtype=np.bool)
    for s in S:
        N = len(s)
        rr, cc = polygon(np.array(s[1:N:2]).clip(max=h-1), \
                      np.array(s[0:N:2]).clip(max=w-1)) # (y, x)
        M[rr, cc] = 1
    return M 
Example #24
Source File: dataset.py    From kraken with Apache License 2.0 5 votes vote down vote up
def add(self, image: Union[str, Image.Image], text: str, baseline: List[Tuple[int, int]], boundary: List[Tuple[int, int]], *args, **kwargs):
        """
        Adds a line to the dataset.

        Args:
            im (path): Path to the whole page image
            text (str): Transcription of the line.
            baseline (list): A list of coordinates [[x0, y0], ..., [xn, yn]].
            boundary (list): A polygon mask for the line.
        """
        for func in self.text_transforms:
            text = func(text)
            if not text:
                raise KrakenInputException('Text line is empty after transformations')
        if self.preload:
            if not isinstance(image, Image.Image):
                im = Image.open(image)
            im, _ = next(extract_polygons(im, {'type': 'baselines', 'lines': [{'baseline': baseline, 'boundary': boundary}]}))
            try:
                im = self.head_transforms(im)
                if not is_bitonal(im):
                    self.im_mode = im.mode
                im = self.tail_transforms(im)
            except ValueError:
                raise KrakenInputException('Image transforms failed on {}'.format(image))
            self._images.append(im)
        else:
            self._images.append((image, baseline, boundary))
        self._gt.append(text)
        self.alphabet.update(text) 
Example #25
Source File: mask_coco2voc.py    From kaggle-rsna18 with MIT License 5 votes vote down vote up
def segToMask( S, h, w ):
    """
    Convert polygon segmentation to binary mask.
    :param   S (float array)   : polygon segmentation mask
    :param   h (int)           : target mask height
    :param   w (int)           : target mask width
    :return: M (bool 2D array) : binary mask
    """
    M = np.zeros((h,w), dtype=np.bool)
    for s in S:
        N = len(s)
        rr, cc = polygon(np.array(s[1:N:2]).clip(max=h-1), \
                      np.array(s[0:N:2]).clip(max=w-1)) # (y, x)
        M[rr, cc] = 1
    return M 
Example #26
Source File: coco.py    From kaggle-rsna18 with MIT License 5 votes vote down vote up
def annToRLE(self, ann):
        """
        Convert annotation which can be polygons, uncompressed RLE to RLE.
        :return: binary mask (numpy 2D array)
        """
        t = self.imgs[ann['image_id']]
        h, w = t['height'], t['width']
        segm = ann['segmentation']
        if type(segm) == list:
            # polygon -- a single object might consist of multiple parts
            # we merge all parts into one mask rle code
            rles = mask.frPyObjects(segm, h, w)
            rle = mask.merge(rles)
        elif type(segm['counts']) == list:
            # uncompressed RLE
            rle = mask.frPyObjects(segm, h, w)
        else:
            # rle
            rle = ann['segmentation']
        return rle 
Example #27
Source File: coco.py    From kaggle-rsna18 with MIT License 5 votes vote down vote up
def segToMask( S, h, w ):
         """
         Convert polygon segmentation to binary mask.
         :param   S (float array)   : polygon segmentation mask
         :param   h (int)           : target mask height
         :param   w (int)           : target mask width
         :return: M (bool 2D array) : binary mask
         """
         M = np.zeros((h,w), dtype=np.bool)
         for s in S:
             N = len(s)
             rr, cc = polygon(np.array(s[1:N:2]).clip(max=h-1), \
                              np.array(s[0:N:2]).clip(max=w-1)) # (y, x)
             M[rr, cc] = 1
         return M 
Example #28
Source File: grasp.py    From mvp_grasp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def polygon_coords(self, shape=None):
        return polygon(self.points[:, 0], self.points[:, 1], shape) 
Example #29
Source File: visualize.py    From kaggle-airbus-ship-detection-challenge with Apache License 2.0 5 votes vote down vote up
def coord2_img(mean_x, mean_y, length, width, rotate, img_size=768, img_base=None):

    return coord_draw(polygon, mean_x, mean_y, length, width, rotate, img_size=img_size, img_base=img_base) 
Example #30
Source File: pose_utils.py    From everybody_dance_now_pytorch with GNU Affero General Public License v3.0 5 votes vote down vote up
def produce_ma_mask(kp_array, img_size, point_radius=4):
    from skimage.morphology import dilation, erosion, square
    mask = np.zeros(shape=img_size, dtype=bool)
    limbs = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10],
              [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17],
               [1,16], [16,18], [2,17], [2,18], [9,12], [12,6], [9,3], [17,18]]
    limbs = np.array(limbs) - 1
    for f, t in limbs:
        from_missing = kp_array[f][0] == MISSING_VALUE or kp_array[f][1] == MISSING_VALUE
        to_missing = kp_array[t][0] == MISSING_VALUE or kp_array[t][1] == MISSING_VALUE
        if from_missing or to_missing:
            continue

        norm_vec = kp_array[f] - kp_array[t]
        norm_vec = np.array([-norm_vec[1], norm_vec[0]])
        norm_vec = point_radius * norm_vec / np.linalg.norm(norm_vec)


        vetexes = np.array([
            kp_array[f] + norm_vec,
            kp_array[f] - norm_vec,
            kp_array[t] - norm_vec,
            kp_array[t] + norm_vec
        ])
        yy, xx = polygon(vetexes[:, 0], vetexes[:, 1], shape=img_size)
        mask[yy, xx] = True

    for i, joint in enumerate(kp_array):
        if kp_array[i][0] == MISSING_VALUE or kp_array[i][1] == MISSING_VALUE:
            continue
        yy, xx = circle(joint[0], joint[1], radius=point_radius, shape=img_size)
        mask[yy, xx] = True

    mask = dilation(mask, square(5))
    mask = erosion(mask, square(5))
    return mask