Python skimage.draw.ellipse() Examples

The following are 8 code examples of skimage.draw.ellipse(). 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 _expand_raster(raster, distance = (4,2)):
    try:
        from skimage import draw, morphology
    except:
        raise ImportError("""
            The fill function requires the module "scikit-image"
            to operate.  Please retry after installing scikit-image:

            $ pip install --upgrade scikit-image """)
    if distance[0] <= 0.5 and distance[1] <= 0.5: return raster

    num_pixels = np.array(np.ceil(distance), dtype = int)
    neighborhood = np.zeros((num_pixels[1]*2+1, num_pixels[0]*2+1), dtype=np.bool)
    rr, cc = draw.ellipse(num_pixels[1], num_pixels[0], distance[1]+0.5, distance[0]+0.5)
    neighborhood[rr, cc] = 1

    return morphology.binary_dilation(image = raster, selem=neighborhood) 
Example #2
Source File: geometry.py    From phidl with MIT License 5 votes vote down vote up
def ellipse(radii = (10,5), angle_resolution = 2.5, layer = 0):
    """Generate an ellipse geometry.

    Parameters
    ----------
    radii : tuple
        Semimajor (x) and semiminor (y) axis lengths of the ellipse.
    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 ellipse polygon in it
    """

    D = Device(name = 'ellipse')
    a = radii[0]
    b = radii[1]
    t = np.linspace(0, 360, int(np.ceil(360/angle_resolution) + 1))*pi/180
    r = a*b/(sqrt((b*cos(t))**2 + (a*sin(t))**2))
    xpts = r*cos(t)
    ypts = r*sin(t)
    D.add_polygon(points = (xpts,ypts), layer = layer)
    return D 
Example #3
Source File: layer.py    From uchroma with GNU Lesser General Public License v3.0 5 votes vote down vote up
def ellipse(self, row: int, col: int, radius_r: float, radius_c: float,
                color: ColorType, fill: bool=False, alpha: float=1.0) -> 'Layer':
        """
        Draw an ellipse centered on the specified row and column,
        with the given radiuses.

        :param row: Center row of ellipse
        :param col: Center column of ellipse
        :param radius_r: Radius of ellipse on y axis
        :param radius_c: Radius of ellipse on x axis
        :param color: Color to draw with
        :param fill: True if the circle should be filled

        :return: This frame instance
        """
        if fill:
            rr, cc = draw.ellipse(row, col, math.floor(radius_r), math.floor(radius_c),
                                  shape=self.matrix.shape)
            self._draw(rr, cc, color, alpha)

        else:
            rr, cc = draw.ellipse_perimeter(row, col, math.floor(radius_r), math.floor(radius_c),
                                            shape=self.matrix.shape)
            self._draw(rr, cc, color, alpha)

        return self 
Example #4
Source File: test_descriptors.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ray_features_ellipse(self):
        seg = np.ones((400, 600), dtype=bool)
        x, y = draw.ellipse(200, 250, 120, 200, rotation=np.deg2rad(30),
                            shape=seg.shape)
        seg[x, y] = False

        points = [(200, 250), (150, 200), (250, 300)]
        for i, point in enumerate(points):
            ray_dist_raw = compute_ray_features_segm_2d(
                seg, point, angle_step=ANGULAR_STEP)
            # ray_dist, shift = seg_fts.shift_ray_features(ray_dist_raw)
            points = reconstruct_ray_features_2d(point, ray_dist_raw)
            p_fig = export_ray_results(seg, point, points, ray_dist_raw, [],
                                       'ellipse-%i.png' % i)
            self.assertTrue(os.path.exists(p_fig)) 
Example #5
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ellipse(r, c, r_radius, c_radius, orientation=0., shape=None):
    """ temporary wrapper until release New version scikit-image v0.13

    .. note:: Should be solved in skimage v0.13

    :param int r: center position in rows
    :param int c: center position in columns
    :param int r_radius: ellipse diam in rows
    :param int c_radius: ellipse diam in columns
    :param float orientation: ellipse orientation
    :param tuple(int,int) shape: size of output mask
    :return tuple(list(int),list(int)): indexes of filled positions

    >>> img = np.zeros((14, 20), dtype=int)
    >>> rr, cc = ellipse(7, 10, 3, 9, np.deg2rad(30), img.shape)
    >>> img[rr, cc] = 1
    >>> img
    array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
           [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    """
    rr, cc = draw.ellipse(r, c, r_radius, c_radius,
                          rotation=orientation, shape=shape)
    # alternative version
    # rr, cc = _ellipse(r, c, r_radius, c_radius, orientation, shape)
    return rr, cc 
Example #6
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ellipse_perimeter(r, c, r_radius, c_radius, orientation=0., shape=None):
    """ see New version scikit-image v0.14

    .. note:: Should be solved in skimage v0.14

    :param int r: center position in rows
    :param int c: center position in columns
    :param int r_radius: ellipse diam in rows
    :param int c_radius: ellipse diam in columns
    :param float orientation: ellipse orientation
    :param tuple(int,int) shape: size of output mask
    :return tuple(list(int),list(int)): indexes of filled positions

    >>> img = np.zeros((14, 20), dtype=int)
    >>> rr, cc = ellipse_perimeter(7, 10, 3, 9, np.deg2rad(30), img.shape)
    >>> img[rr, cc] = 1
    >>> img
    array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
           [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
           [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
           [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    """
    rr, cc = draw.ellipse_perimeter(r, c, r_radius, c_radius,
                                    orientation=-orientation, shape=shape)
    return rr, cc 
Example #7
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def figure_ellipse_fitting(img, seg, ellipses, centers, crits, fig_size=9):
    """ show figure with result of the ellipse fitting

    :param ndarray img: image
    :param ndarray seg: segmentation
    :param list(tuple(int,int,int,int,float)) ellipses: collection of ellipse parameters
        ell. parameters: (x, y, height, width, orientation)
    :param list(tuple(int,int)) centers: points
    :param list(float) crits:
    :param float fig_size: maximal figure size
    :return Figure:

    >>> img = np.random.random((100, 150, 3))
    >>> seg = np.random.randint(0, 2, (100, 150))
    >>> ells = np.random.random((3, 5)) * 25
    >>> centers = np.random.random((3, 2)) * 25
    >>> crits = np.random.random(3)
    >>> fig = figure_ellipse_fitting(img[:, :, 0], seg, ells, centers, crits)
    >>> isinstance(fig, matplotlib.figure.Figure)
    True
    """
    assert len(ellipses) == len(centers) == len(crits), \
        'number of ellipses (%i) and centers (%i) and criteria (%i) ' \
        'should match' % (len(ellipses), len(centers), len(crits))

    fig, ax = create_figure_by_image(img.shape[:2], fig_size)
    assert img.ndim == 2, \
        'required image dimension is 2 to instead %r' % img.shape
    ax.imshow(img, cmap=plt.cm.Greys_r)

    for i, params in enumerate(ellipses):
        c1, c2, h, w, phi = params
        rr, cc = ellipse_perimeter(int(c1), int(c2), int(h), int(w), phi)
        ax.plot(cc, rr, '.', color=COLORS[i % len(COLORS)],
                label='#%i with crit=%d' % ((i + 1), int(crits[i])))
    ax.legend(loc='lower right')

    # plt.plot(centers[:, 1], centers[:, 0], 'ow')
    for i in range(len(centers)):
        ax.plot(centers[i, 1], centers[i, 0], 'o',
                color=COLORS[i % len(COLORS)])
    ax.set(xlim=[0, seg.shape[1]], ylim=[seg.shape[0], 0])
    ax.axis('off')
    fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
    return fig 
Example #8
Source File: drawing.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def draw_eggs_ellipse(mask_shape, pos_ant, pos_lat, pos_post,
                      threshold_overlap=0.6):
    """ from given 3 point estimate the ellipse

    :param tuple(int,int) mask_shape:
    :param [tuple(int,int)] pos_ant: anterior
    :param [tuple(int,int)] pos_lat: latitude
    :param [tuple(int,int)] pos_post: postlude
    :param float threshold_overlap:
    :return ndarray:

    >>> pos_ant, pos_lat, pos_post = [10, 10], [20, 20], [35, 20]
    >>> points = np.array([pos_ant, pos_lat, pos_post])
    >>> _= plt.plot(points[:, 0], points[:, 1], 'og')
    >>> mask = draw_eggs_ellipse([30, 50], [pos_ant], [pos_lat], [pos_post])
    >>> mask.shape
    (30, 50)
    >>> _= plt.imshow(mask, alpha=0.5, interpolation='nearest')
    >>> _= plt.xlim([0, mask.shape[1]]), plt.ylim([0, mask.shape[0]]), plt.grid()
    >>> # plt.show()
    """
    mask_eggs = np.zeros(mask_shape)
    for i, (ant, lat, post) in enumerate(zip(pos_ant, pos_lat, pos_post)):
        ant, lat, post = map(np.array, [ant, lat, post])
        center = ant + (post - ant) / 2.
        lat_proj = closest_point_on_line(ant, post, lat)
        # http://stackoverflow.com/questions/433371/ellipse-bounding-a-rectangle
        radius_a = (np.linalg.norm(post - ant) / 2. / np.sqrt(2)) * 1.
        radius_b = (np.linalg.norm(lat - lat_proj) / np.sqrt(2)) * 1.
        angle = np.arctan2(*(post - ant))
        rr, cc = ellipse(int(center[1]), int(center[0]),
                         int(radius_a), int(radius_b),
                         orientation=angle, shape=mask_eggs.shape)
        mask = np.zeros(mask_shape)
        mask[rr, cc] = True

        # mask = ndimage.morphology.binary_fill_holes(mask)
        # distance = ndimage.distance_transform_edt(mask)
        # probab = distance / np.max(distance)
        # mask = probab >= threshold_dist

        m_overlap = np.sum(np.logical_and(mask > 0, mask_eggs > 0)) / float(np.sum(mask))
        if m_overlap > threshold_overlap:
            logging.debug('skip egg drawing while it overlap by %f', m_overlap)
            continue
        mask_eggs[mask.astype(bool)] = i + 1

    return mask_eggs