def test_hough_ellipse_non_zero_angle():
    img = np.zeros((20, 20), dtype=int)
    a = 6
    b = 9
    x0 = 10
    y0 = 10
    angle = np.pi / 1.35
    rr, cc = ellipse_perimeter(x0, x0, b, a, orientation=angle)
    img[rr, cc] = 1
    result = tf.hough_ellipse(img, threshold=15, accuracy=3)
    assert_almost_equal(result[0][0] / 100., x0 / 100., decimal=1)
    assert_almost_equal(result[0][1] / 100., y0 / 100., decimal=1)
    assert_almost_equal(result[0][2] / 100., b / 100., decimal=1)
    assert_almost_equal(result[0][3] / 100., a / 100., decimal=1)
    assert_almost_equal(result[0][4], angle, decimal=1)
Esempio n. 2
0
def test_hough_ellipse_zero_angle():
    img = np.zeros((25, 25), dtype=int)
    rx = 6
    ry = 8
    x0 = 12
    y0 = 15
    angle = 0
    rr, cc = ellipse_perimeter(y0, x0, ry, rx)
    img[rr, cc] = 1
    result = transform.hough_ellipse(img, threshold=9)
    best = result[-1]
    assert_equal(best[1], y0)
    assert_equal(best[2], x0)
    assert_almost_equal(best[3], ry, decimal=1)
    assert_almost_equal(best[4], rx, decimal=1)
    assert_equal(best[5], angle)
    # Check if I re-draw the ellipse, points are the same!
    # ie check API compatibility between hough_ellipse and ellipse_perimeter
    rr2, cc2 = ellipse_perimeter(y0,
                                 x0,
                                 int(best[3]),
                                 int(best[4]),
                                 orientation=best[5])
    assert_equal(rr, rr2)
    assert_equal(cc, cc2)
Esempio n. 3
0
def test_hough_ellipse_non_zero_posangle2():
    # ry < rx, angle in [0:pi/2]
    img = np.zeros((30, 24), dtype=int)
    rx = 12
    ry = 6
    x0 = 10
    y0 = 15
    angle = np.pi / 1.35
    rr, cc = ellipse_perimeter(y0, x0, ry, rx, orientation=angle)
    img[rr, cc] = 1
    result = tf.hough_ellipse(img, threshold=15, accuracy=3)
    result.sort(order='accumulator')
    best = result[-1]
    assert_almost_equal(best[1] / 100., y0 / 100., decimal=1)
    assert_almost_equal(best[2] / 100., x0 / 100., decimal=1)
    assert_almost_equal(best[3] / 10., ry / 10., decimal=1)
    assert_almost_equal(best[4] / 100., rx / 100., decimal=1)
    assert_almost_equal(best[5], angle, decimal=1)
    # Check if I re-draw the ellipse, points are the same!
    # ie check API compatibility between hough_ellipse and ellipse_perimeter
    rr2, cc2 = ellipse_perimeter(y0,
                                 x0,
                                 int(best[3]),
                                 int(best[4]),
                                 orientation=best[5])
    assert_equal(rr, rr2)
    assert_equal(cc, cc2)
Esempio n. 4
0
def test_ellipse_perimeter_shape():
    img = np.zeros((15, 20), 'uint8')
    rr, cc = ellipse_perimeter(7, 10, 9, 9, 0, shape=(15, 20))
    img[rr, cc] = 1
    shift = 5
    img_ = np.zeros((15 + 2 * shift, 20), 'uint8')
    rr, cc = ellipse_perimeter(7 + shift, 10, 9, 9, 0, shape=None)
    img_[rr, cc] = 1
    assert_array_equal(img, img_[shift:-shift, :])
Esempio n. 5
0
def test_ellipse_perimeter_shape():
    img = np.zeros((15, 20), 'uint8')
    rr, cc = ellipse_perimeter(7, 10, 9, 9, 0, shape=(15, 20))
    img[rr, cc] = 1
    shift = 5
    img_ = np.zeros((15 + 2 * shift, 20), 'uint8')
    rr, cc = ellipse_perimeter(7 + shift, 10, 9, 9, 0, shape=None)
    img_[rr, cc] = 1
    assert_array_equal(img, img_[shift:-shift, :])
Esempio n. 6
0
def enclosing_ellipse(beam1, beam2):
    bmaj1, bmin1, bpa1 = beam1
    bmaj2, bmin2, bpa2 = beam2

    if bmaj1 <= bmin2:
        return (bmaj2, bmin2, bpa2)
    if bmaj2 <= bmin1:
        return (bmaj1, bmin1, bpa1)
    if np.logical_and.reduce(
        (bmaj1 == bmaj2, bmin1 == bmin2, ((bpa1 - bpa2) % np.pi) == 0)):
        return (bmaj1, bmin1, bpa1)

    if bmaj2 < bmaj1:
        tmp = bmaj2
        bmaj2 = bmaj1
        bmaj1 = tmp
        tmp = bmin2
        bmin2 = bmin1
        bmin1 = tmp
        tmp = bpa2
        bpa2 = bpa1
        bpa1 = tmp

    dpa = bpa1

    bpa1 -= dpa
    bpa2 -= dpa

    Y = bmaj1 / bmin1
    A = r_e(bmaj2, bmin2, bpa2, t_m(bmaj2, bmin2, bpa2, Y), y=Y)
    B = max([
        r_e(bmaj2, bmin2, bpa2, t_m(bmaj2, bmin2, bpa2, Y) + 0.5 * np.pi, y=Y),
        bmaj1
    ])

    #(mx,my)= ellipse (bmaj2,bmin2,bpa2,t_m(bmaj2,bmin2,bpa2,Y);y=Y)
    (mx, my) = ellipse_perimeter(0, 0, bmin2, bmaj2, orientation=bpa2)
    P = np.arctan2(my, mx)

    print(bmin2, bmaj2, bpa2)
    print(A, B, P)
    a = r_e(A, B, P, t_m(A, B, P, 1. / Y), y=1. / Y)
    b = r_e(A, B, P, t_m(A, B, P, 1. / Y) + 0.5 * np.pi, y=1. / Y)
    # (mx,my)= ellipse (A,B,P,t_m(A,B,P,1./Y),y=1./Y)
    (mx, my) = ellipse_perimeter(0, 0, A, B, orientation=P)
    p = np.arctan2(my, mx)
    p += dpa

    if b > a:
        (a, b, p) = (b, a, p + 0.5 * np.pi
                     )  # make sure that 'a' is the semimajor axis
    return (a, b, p % np.pi)
Esempio n. 7
0
def plot_segmap_ellpreds(image, seg_map, pupil_ellipse, iris_ellipse):
    loc_iris = seg_map == 1
    loc_pupil = seg_map == 2

    out_image = np.stack([image] * 3, axis=2)

    alphaBlend = 20

    loc_image_non_sat = image < (255 - alphaBlend)

    # Add green to iris
    out_image[...,
              1] = out_image[...,
                             1] + alphaBlend * loc_iris * loc_image_non_sat

    # Add yellow to pupil

    out_image[...,
              0] = out_image[...,
                             0] + alphaBlend * loc_pupil * loc_image_non_sat
    out_image[...,
              1] = out_image[...,
                             1] + alphaBlend * loc_pupil * loc_image_non_sat

    # Sketch iris ellipse
    if not np.all(iris_ellipse == -1):
        [rr_i, cc_i] = draw.ellipse_perimeter(int(iris_ellipse[1]),
                                              int(iris_ellipse[0]),
                                              int(iris_ellipse[3]),
                                              int(iris_ellipse[2]),
                                              orientation=iris_ellipse[4])
        rr_i = rr_i.clip(6, image.shape[0] - 6)
        cc_i = cc_i.clip(6, image.shape[1] - 6)
        out_image[rr_i, cc_i, ...] = np.array([0, 0, 255])

    if not np.all(pupil_ellipse == -1):
        # Sketch pupil ellipse
        [rr_p, cc_p] = draw.ellipse_perimeter(int(pupil_ellipse[1]),
                                              int(pupil_ellipse[0]),
                                              int(pupil_ellipse[3]),
                                              int(pupil_ellipse[2]),
                                              orientation=pupil_ellipse[4])

        rr_p = rr_p.clip(6, image.shape[0] - 6)
        cc_p = cc_p.clip(6, image.shape[1] - 6)
        out_image[rr_p, cc_p, ...] = np.array([255, 0, 0])

    return out_image
Esempio n. 8
0
    def animate(i):
        plt.title('Frame %d' % i)

        slice_data = preprocess_data(data[i + 100])

        if np.count_nonzero(slice_data):
            labeled_data, num_features = segment_data(slice_data)

            stats = slice_stats(labeled_data)
            stats = stats[(stats.area > 20) & ((stats.major_axis_length < frame_shape[0]) | (stats.major_axis_length < frame_shape[1]))]
            stats = stats[stats.circularity > 0.5]

            for index, row in stats.iterrows():
                print 'Frame# %d, Circle# %d [circularity = %f]' % (i, row.label, row.circularity)

                yc, xc = [int(round(x)) for x in row.centroid]
                orientation = row.orientation
                major_axis = int(round(row.major_axis_length/2.))
                minor_axis = int(round(row.minor_axis_length/2.))

                slice_data = ski.color.gray2rgb(slice_data)

                cy, cx = ellipse_perimeter(yc, xc, minor_axis, major_axis, orientation)
                slice_data[cy, cx] = (220, 20, 20)

                rr, cc = circle(yc, xc, 2)
                slice_data[rr, cc] = (220, 20, 20)

        im.set_data(slice_data)

        return im,
Esempio n. 9
0
def random_walker():
    plt.close("all")
    p = Path(
        'C:/Users/fshaw/Documents/PycharmProjects/tilapia/data/raw/padded_images/2015_00T2A6_A.JPG'
    )
    image = io.imread(p)
    image_gray = color.rgb2gray(image)
    image_labels = np.zeros(image_gray.shape, dtype=np.uint8)
    points = circle_points(resolution=40, center=[250, 250], radius=160)[:-1]

    # indices = draw.circle_perimeter(130, 250, 100)
    indices = draw.ellipse_perimeter(250, 250, r_radius=30, c_radius=200)
    image_labels[indices] = 1
    image_labels[points[:, 1].astype(np.int), points[:, 0].astype(np.int)] = 2
    image_show(image_labels)

    image_segmented = seg.random_walker(image_gray,
                                        image_labels,
                                        mode='bf',
                                        beta=200,
                                        tol=1.e-3)  # Check our results
    fig, ax = image_show(image_gray)
    ax.imshow(image_segmented == 1, alpha=0.3)

    plt.show()
Esempio n. 10
0
def elip(image):
    image_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    edges = canny(image_gray, sigma=2.0,low_threshold=0.55, high_threshold=0.8)
    # Perform a Hough Transform
    # The accuracy corresponds to the bin size of a major axis.
    # The value is chosen in order to get a single high accumulator.
    # The threshold eliminates low accumulators
    result = hough_ellipse(edges, accuracy=20, threshold=250,
                        min_size=100, max_size=120)
    result.sort(order='accumulator')

    # Estimated parameters for the ellipse
    best = list(result[-1])
    yc, xc, a, b = [int(round(x)) for x in best[1:5]]
    orientation = best[5]

    # Draw the ellipse on the original image
    cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
    image_rgb[cy, cx] = (0, 0, 255)
    # Draw the edge (white) and the resulting ellipse (red)
    edges = color.gray2rgb(img_as_ubyte(edges))
    edges[cy, cx] = (250, 0, 0)

    fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True,
                                    sharey=True,
                                    subplot_kw={'adjustable':'box-forced'})

    ax1.set_title('Original picture')
    ax1.imshow(image_rgb)

    ax2.set_title('Edge (white) and result (red)')
    ax2.imshow(edges)
def draw_error_ellipse2d(image, mu, sigma, color="k"):
    if image.shape[2] != 3:
        print('The input image should has 3 channels')
    else:
        eigen_values, eigen_vecters = np.linalg.eigh(sigma)
        angle = np.arctan2(eigen_vecters[1,1], eigen_vecters[0,0])
        angle = angle/np.pi*180
        # 95%---5.991     90%---4.605     99%---9.21
        x_value = np.sqrt(eigen_values[0]*5.991)
        y_value = np.sqrt(eigen_values[1]*5.991)
        points = draw.ellipse_perimeter(int(mu[1]), int(mu[0]), int(y_value), int(x_value), angle)
        pointsr = points[0]
        pointsc = points[1]

        (sizerow, sizecol, _) = image.shape
        valid_points_r = []
        valid_points_c = []
        for i in range(len(pointsr)):
            if pointsr[i] > 0 and pointsc[i] > 0 and pointsr[i] < sizerow and pointsc[i] < sizecol:
                valid_points_r.append(pointsr[i])
                valid_points_c.append(pointsc[i])
        
        if color=='k':
          image[valid_points_r, valid_points_c, 1] = 255
        else: image[valid_points_r, valid_points_c, 1] = 0
    return image
Esempio n. 12
0
def reference_circle(coords, dimX, dimY, radius):
    """Draw the perimeter of an circle at a given position in the diffraction
    pattern (e.g. to provide a reference for finding the direct beam center).

    Parameters
    ----------
    coords : np.array size n,2
        size n,2 array of coordinates to draw the circle.
    dimX : int
        first dimension of the diffraction pattern (size)
    dimY : int
        second dimension of the diffraction pattern (size)
    radius : int
        radius of the circle to be drawn

    Returns
    -------
    img: np.array
        Array containing the circle at the position given in the coordinates.
    """
    img = np.zeros((dimX, dimY))

    for n in range(np.size(coords, 0)):
        rr, cc = ellipse_perimeter(coords[n, 0], coords[n, 1], radius, radius)
        img[rr, cc] = 1

    return img
def outerEllipse(innerEllipseParam):
    '''outer ellipse'''
    outerBoundary = 5
    outerEllipseParam = innerEllipseParam
    outerEllipseParam[
        'ellipseSemiY'] = innerEllipseParam['ellipseSemiY'] + outerBoundary
    outerEllipseParam[
        'ellipseSemiX'] = innerEllipseParam['ellipseSemiX'] + outerBoundary
    rrOuter, ccOuter = ellipse_perimeter(
        outerEllipseParam['ellipseCenterY'],
        outerEllipseParam['ellipseCenterX'],
        outerEllipseParam['ellipseSemiY'],
        outerEllipseParam['ellipseSemiX'],
        orientation=outerEllipseParam['orientation'])
    outerEllipseVerts = np.dstack([rrOuter, ccOuter])[0]
    edgePoints = []

    points = [i for i in outerEllipseVerts if i[1] == 0]  # y=0的两个点

    maxXOuterEllipse = max(outerEllipseVerts, key=lambda x: x[0])[0]
    minXOuterEllipse = min(outerEllipseVerts, key=lambda x: x[0])[0]

    rightPoints = [i for i in outerEllipseVerts if i[0] == maxXOuterEllipse]
    leftPoints = [i for i in outerEllipseVerts if i[0] == minXOuterEllipse]
    rightPoints = np.asarray(rightPoints)
    leftPoints = np.asarray(leftPoints)
    edgePoints.append(np.mean(rightPoints, axis=0))  # 最左边和最右边的两个点
    edgePoints.append(np.mean(leftPoints, axis=0))
    edgePoints = edgePoints + points

    return outerEllipseVerts, edgePoints
 def _ellipses(self, color, size): 
     new_clusters = []
     image_shape = self.cluster_masks[color].shape
     for cluster in self.cluster_props[color]:
         test_mask = np.zeros(image_shape, bool)
     
         centroid = cluster.centroid
         ycenter = int(round(centroid[0]))
         xcenter = int(round(centroid[1]))
         
         major_axis = int(round(cluster.major_axis_length/2 * size)) 
         minor_axis = int(round(cluster.minor_axis_length/2 * size))
         orientation = cluster.orientation
     
         if (major_axis < 1 or minor_axis < 1):
             major_axis = 1
             minor_axis = 1
            
         rr, cc  = ellipse_perimeter(ycenter,xcenter,major_axis,minor_axis,orientation,image_shape)
         test_mask[rr,cc] = True
         test_mask  = ndimage.morphology.binary_fill_holes(test_mask)
         test_mask = np.where(test_mask == True, 1, 0)
         new_cluster = measure.regionprops(test_mask, coordinates='xy')
         new_clusters += new_cluster
     self.cluster_props[color] = new_clusters
Esempio n. 15
0
def ellipse_perimeter(r, c, r_radius, c_radius, orientation=0., shape=None):
    """ see New version scikit-image 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 (int, int) shape: size of output mask
    :return ([int], [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
Esempio n. 16
0
def draw_ell(img, x, y, rmin, rmaj, posang):
    #returns rr,cc: index px that belong to the ellipse perimeter.
    rr, cc = ellipse_perimeter(
        x, y, rmin, rmaj, orientation=posang
    )  #(x,y) center coord., posang major axis orientation clockwise [rad]
    img[rr, cc] = 1
    return img
Esempio n. 17
0
def img_generate_counter(img, bboxes):
    subimages, bboxes = cropImage(img, bboxes)
    y_points = np.array([])
    x_points = np.array([])
    defect_img_List = list()
    for subim, bbox in zip(subimages, bboxes):
        defects_Dict = dict()
        defects_X_List = list()
        defects_Y_List = list()
        region1 = flood_fitting(subim)
        result = (int(region1['centroid'][0] + bbox[0]),
                  int(region1['centroid'][1] + bbox[1]),
                  int(region1['minor_axis_length'] / 2),
                  int(region1['major_axis_length'] / 2),
                  -region1['orientation'])
        rr, cc = draw.ellipse_perimeter(*result)
        # rr is row which is x in pixel
        # cc is column which is y in pixel
        # (rr,cc) represents one data points and there may be redundent data points
        assert len(rr) == len(cc)
        for i in range(len(cc)):
            print(cc[i])
        y_points = np.concatenate((y_points, rr))
        x_points = np.concatenate((x_points, cc))
    fig = plt.figure(figsize=(10, 10))
    plt.imshow(img[0, :, :], cmap='gray')
    plt.scatter(x_points, y_points, s=(1 * 72. / fig.dpi)**2, alpha=0.5)
Esempio n. 18
0
def test_ellipse_perimeter_dot_nzeroangle():
    # dot, angle != 0
    img = np.zeros((30, 15), 'uint8')
    rr, cc = ellipse_perimeter(15, 7, 0, 0, 1)
    img[rr, cc] = 1
    assert (np.sum(img) == 1)
    assert (img[15][7] == 1)
Esempio n. 19
0
def hough_ellipse_finder(I_sub):
    """
    Uses the ellipse hough transform to find ellipses. Use if the bw theshold method fails.
    :param I_sub: The ROI image from which to extract the ellipses
    :return: innner,outer ellipse points.
    """
    edges = feature.canny(I_sub, sigma=2.0)
    result = transform.hough_ellipse(edges,
                                     accuracy=20,
                                     threshold=250,
                                     min_size=100)
    result.sort(order='accumulator')

    for ii in range(len(result)):
        ellip = list(result[-ii])
        yc, xc, a, b = [int(round(x)) for x in ellip[1:5]]
        orientation = ellip[5]

        # Draw the ellipse on the original image
        cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
        cy = cy[cy < I_sub.shape[0]]
        cx = cx[cx < I_sub.shape[1]]
        # Draw the edge (white) and the resulting ellipse (red)
        Itemp = color.gray2rgb(I_sub)
        Itemp[cy, cx] = (250, 0, 0)
        plt.imshow(Itemp)
        plt.pause(1)
Esempio n. 20
0
def gen_ellipse_contour_perim(perim, color="r"):
    # Vertices
    input_points = np.where(perim == 1)
    if (np.unique(input_points[0]).shape[0]) < 6 or (np.unique(
            input_points[1]).shape[0] < 6):
        return None, None, None, None, None, None, None
    else:
        try:
            vertices = np.array([input_points[0], input_points[1]]).T
            # Contour
            fitted = LSqEllipse()
            fitted.fit([vertices[:, 1], vertices[:, 0]])
            center, w, h, radian = fitted.parameters()
            ell = mpl.patches.Ellipse(xy=[center[0], center[1]],
                                      width=w * 2,
                                      height=h * 2,
                                      angle=np.rad2deg(radian),
                                      fill=False,
                                      color=color)
            # Because of the np indexing of y-axis, orientation needs to be minus
            rr, cc = ellipse_perimeter(int(np.round(center[0])),
                                       int(np.round(center[1])),
                                       int(np.round(w)), int(np.round(h)),
                                       -radian)
            return rr, cc, center, w, h, radian, ell
        except:
            return None, None, None, None, None, None, None
Esempio n. 21
0
def test_ellipse_perimeter_dot_zeroangle():
    # dot, angle == 0
    img = np.zeros((30, 15), "uint8")
    rr, cc = ellipse_perimeter(15, 7, 0, 0, 0)
    img[rr, cc] = 1
    assert np.sum(img) == 1
    assert img[15][7] == 1
Esempio n. 22
0
def test_ellipse_perimeter_dot_nzeroangle():
    # dot, angle != 0
    img = np.zeros((30, 15), 'uint8')
    rr, cc = ellipse_perimeter(15, 7, 0, 0, 1)
    img[rr, cc] = 1
    assert(np.sum(img) == 1)
    assert(img[15][7] == 1)
Esempio n. 23
0
    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
Esempio n. 24
0
def draw_ellipse(ellipse, on_img, with_color=None):
    with_color = with_color or utils.make_n_colors(1)[0]
    _, yc, xc, a, b, orientation = ellipse
    py, px = ellipse_perimeter(to_int(yc), to_int(xc), to_int(a), to_int(b), orientation)
    on_img[py, px] = with_color

    # draw axes
    draw_ellipse_axes(on_img, yc, xc, a, b, orientation, with_color)
Esempio n. 25
0
def make_image():
    im = (np.ones((201, 201, 3)) * 255).astype(np.uint8)
    rr, cc = draw.ellipse_perimeter(100,
                                    100,
                                    30,
                                    70,
                                    orientation=math.radians(17))
    im[rr, cc] = (0, 0, 0)
    return im
def test_hough_ellipse_non_zero_negangle4():
    # ry < rx, angle in [-pi:-3pi/4]
    img = np.zeros((30, 24), dtype=int)
    rx = 12
    ry = 6
    x0 = 10
    y0 = 15
    angle = -np.pi / 1.35 - np.pi
    rr, cc = ellipse_perimeter(y0, x0, ry, rx, orientation=angle)
    img[rr, cc] = 1
    result = tf.hough_ellipse(img, threshold=15, accuracy=3)
    result.sort(order="accumulator")
    best = result[-1]
    # Check if I re-draw the ellipse, points are the same!
    # ie check API compatibility between hough_ellipse and ellipse_perimeter
    rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]), orientation=best[5])
    assert_equal(rr, rr2)
    assert_equal(cc, cc2)
Esempio n. 27
0
def test_ellipse_perimeter_flat_zeroangle():
    # flat ellipse
    img = np.zeros((20, 18), 'uint8')
    img_ = np.zeros((20, 18), 'uint8')
    rr, cc = ellipse_perimeter(6, 7, 0, 5, 0)
    img[rr, cc] = 1
    rr, cc = line(6, 2, 6, 12)
    img_[rr, cc] = 1
    assert_array_equal(img, img_)
Esempio n. 28
0
def test_ellipse_perimeter_flat_zeroangle():
    # flat ellipse
    img = np.zeros((20, 18), 'uint8')
    img_ = np.zeros((20, 18), 'uint8')
    rr, cc = ellipse_perimeter(6, 7, 0, 5, 0)
    img[rr, cc] = 1
    rr, cc = line(6, 2, 6, 12)
    img_[rr, cc] = 1
    assert_array_equal(img, img_)
Esempio n. 29
0
def test_ellipse_perimeter():
    img = np.zeros((30, 15), 'uint8')
    rr, cc = ellipse_perimeter(15, 7, 0, 0)
    img[rr, cc] = 1
    assert(np.sum(img) == 1)
    assert(img[15][7] == 1)

    img = np.zeros((30, 15), 'uint8')
    rr, cc = ellipse_perimeter(15, 7, 14, 6)
    img[rr, cc] = 1
    img_ = np.array(
      [[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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]]
    )

    assert_array_equal(img, img_)
Esempio n. 30
0
def test_hough_ellipse_non_zero_negangle4():
    # ry < rx, angle in [-pi:-3pi/4]
    img = np.zeros((30, 24), dtype=int)
    rx = 12
    ry = 6
    x0 = 10
    y0 = 15
    angle = - np.pi / 1.35 - np.pi
    rr, cc = ellipse_perimeter(y0, x0, ry, rx, orientation=angle)
    img[rr, cc] = 1
    result = tf.hough_ellipse(img, threshold=15, accuracy=3)
    result.sort(order='accumulator')
    best = result[-1]
    # Check if I re-draw the ellipse, points are the same!
    # ie check API compatibility between hough_ellipse and ellipse_perimeter
    rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]),
                                 orientation=best[5])
    assert_equal(rr, rr2)
    assert_equal(cc, cc2)
Esempio n. 31
0
def ONH_Segmentation(im_orig, model, max_ind_0, max_ind_1, ONH_box_size):

    numSegments = 200

    im = im_orig[:, :, 1]
    im_red = im_orig[:, :, 0]
    im_blue = im_orig[:, :, 2]

    feature_mat_norm_test, segments = FMC.create_feature_mat_classify(
        im_orig, im_red, im, im_blue, numSegments)
    decision_results = model.decision_function(feature_mat_norm_test)

    segments2 = segments.copy().astype('float')
    for i in range(numSegments):
        segments2[segments == i] = decision_results[i]
    segment_result1 = cv2.blur(segments2, (9, 9))

    bin_result = segment_result1 > 0

    ret, labels = cv2.connectedComponents(bin_result.astype(np.uint8))
    regions = regionprops(labels)

    max_region_area = 0
    for region in regions:
        if region.area > max_region_area:
            max_region_label = region.label
            max_region_area = region.area

    labels = labels == max_region_label

    selem = disk(27)
    label_close = closing(labels + 0, selem=selem)
    edges = canny(label_close,
                  sigma=2.0,
                  low_threshold=0.55,
                  high_threshold=0.8)

    result = hough_ellipse(edges,
                           accuracy=40,
                           threshold=40,
                           min_size=40,
                           max_size=60)
    result.sort(order='accumulator')

    best = list(result[-1])
    yc, xc, a, b = [int(round(x)) for x in best[1:5]]
    orientation = best[5]
    # Draw the ellipse on the original image
    cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
    im_orig[cy, cx] = (0, 0, 255)

    cx_real_axes = cx + max_ind_1 - ONH_box_size
    cy_real_axes = cy + max_ind_0 - ONH_box_size

    return cx_real_axes, cy_real_axes
Esempio n. 32
0
def main(argv):
    if len(argv) == 0:
        print("Please specify input and output image files.")

    if len(argv) == 1:
        print("Please specify an output image file.")

    input_image_path = argv[0]
    output_image_path = argv[1]

    # Used for shape matching
    ellipse_image = make_ellipse_image(50, 100, 40, 80)
    threshold_ellipse = canny_threshold(ellipse_image, 40, 2)

    ellipse_image_contours, contours, hierarchy = cv2.findContours(threshold_ellipse, cv2.RETR_TREE,
                                                                   cv2.CHAIN_APPROX_SIMPLE)
    ellipse_contour = contours[1]

    # Input image
    image = cv2.imread(input_image_path)
    height, width = image.shape[:2]

    threshold_image = canny_threshold(image, 40, 2)
    kernel = np.ones((5, 5), np.uint8)
    threshold_image = cv2.morphologyEx(threshold_image, cv2.MORPH_DILATE, kernel)
    image_contours, contours, hierarchy = cv2.findContours(threshold_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        major_axis, minor_axis = get_axes(contour)

        # If contour too small
        if not is_good_distance(contour, 10, 10):
            continue

        # If shape too large
        if major_axis > width * 0.70 or minor_axis > height * 0.70:
            continue

        # Match the current contour with ellipse shape contour
        ret = cv2.matchShapes(ellipse_contour, contour, 2, 0)

        # Key parameter
        if ret > 0.75:
            continue

        # Draw an ellipse in the image
        most_left, most_right, most_top, most_bottom = corners(contour)

        center_y = int((most_top[1] + most_bottom[1]) / 2)
        center_x = int((most_right[0] + most_left[0]) / 2)

        cy, cx = ellipse_perimeter(center_y, center_x, int(major_axis / 2), int(minor_axis / 2), math.radians(90))
        image[cy, cx] = (0, 255, 0)

    cv2.imwrite(output_image_path, image)
Esempio n. 33
0
def show_fitted_ellipse(img):
    """
    Show fitted ellipse on the image
    :param img: img in CHW format
    :return: plot ellipse on top of the image
    """
    region1 = flood_fitting(img)
    rr, cc = draw.ellipse_perimeter(int(region1['centroid'][0]), int(region1['centroid'][1]),
                                    int(region1['minor_axis_length'] / 2),
                                    int(region1['major_axis_length'] / 2), -region1['orientation'], img.shape[1:])
    plt.imshow(img[1,:,:], cmap='gray')
    plt.plot(cc, rr, '.')
def test_hough_ellipse_zero_angle():
    img = np.zeros((25, 25), dtype=int)
    rx = 6
    ry = 8
    x0 = 12
    y0 = 15
    angle = 0
    rr, cc = ellipse_perimeter(y0, x0, ry, rx)
    img[rr, cc] = 1
    result = tf.hough_ellipse(img, threshold=9)
    best = result[-1]
    assert_equal(best[1], y0)
    assert_equal(best[2], x0)
    assert_almost_equal(best[3], ry, decimal=1)
    assert_almost_equal(best[4], rx, decimal=1)
    assert_equal(best[5], angle)
    # Check if I re-draw the ellipse, points are the same!
    # ie check API compatibility between hough_ellipse and ellipse_perimeter
    rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]), orientation=best[5])
    assert_equal(rr, rr2)
    assert_equal(cc, cc2)
Esempio n. 35
0
    def draw_female(self,
                    color=(255, 0, 0),
                    thickness=2,
                    show_head_location=True):
        """Draws an ellipse perimeter around a female.

        Parameters
        ----------
        color : 3-tuple
            Color of ellipse outline.
        thickness : int
            Thickness of ellipse outline.
        show_head_location : bool (optional, default=True)
            If true, will draw an arrow from female's rear->head.

        Returns
        -------
        image : 3D np.ndarray of shape [arena.background_image.shape]
            Background image with female surrounded by ellipse.
        """
        image = self.arena.background_image.copy()

        # convert to color
        image = gray2rgb(image)
        assert image.dtype == np.uint8, "image is not of type uint8"

        if self.maj_ax_rad <= 1:
            return image

        rr, cc = ellipse_perimeter(
            self.center[0],
            self.center[1],
            self.min_ax_rad,
            self.maj_ax_rad,
            orientation=(self.orientation * np.pi /
                         180),  # Negating this value 
            # gives good results in test_trk_female.py
            # but leads to improperly oriented ellipse in
            # the gui display.
            shape=self.arena.background_image.shape)
        ellipse_outline_mask = np.zeros_like(self.arena.background_image)
        ellipse_outline_mask[rr, cc] = 1
        dilated_ellipse_outline = dilation(ellipse_outline_mask,
                                           disk(thickness))
        rr, cc = np.where(dilated_ellipse_outline)
        image[rr, cc, :] = color

        if show_head_location:
            rr, cc = line(self.center[0], self.center[1], self.head[0],
                          self.head[1])
            image[rr, cc] = color

        return image
def plot_segmap_ellpreds(image, seg_map, pupil_ellipse, iris_ellipse):
    loc_iris = seg_map == 1
    loc_pupil = seg_map == 2

    out_image = np.stack([image] * 3, axis=2)

    loc_image_non_sat = image < (255 - 100)

    # Add green to iris
    out_image[..., 1] = out_image[..., 1] + 100 * loc_iris * loc_image_non_sat

    # Add yellow to pupil

    out_image[..., 0] = out_image[..., 0] + 100 * loc_pupil * loc_image_non_sat
    out_image[..., 1] = out_image[..., 1] + 100 * loc_pupil * loc_image_non_sat

    # Sketch iris ellipse
    [rr_i, cc_i] = draw.ellipse_perimeter(round(iris_ellipse[1]),
                                          round(iris_ellipse[0]),
                                          round(iris_ellipse[3]),
                                          round(iris_ellipse[2]),
                                          orientation=iris_ellipse[4])

    # Sketch pupil ellipse
    [rr_p, cc_p] = draw.ellipse_perimeter(round(pupil_ellipse[1]),
                                          round(pupil_ellipse[0]),
                                          round(pupil_ellipse[3]),
                                          round(pupil_ellipse[2]),
                                          orientation=pupil_ellipse[4])

    # Clip the perimeter display incase it goes outside bounds
    rr_i = rr_i.clip(6, image.shape[0] - 6)
    rr_p = rr_p.clip(6, image.shape[0] - 6)
    cc_i = cc_i.clip(6, image.shape[1] - 6)
    cc_p = cc_p.clip(6, image.shape[1] - 6)

    out_image[rr_i, cc_i, ...] = np.array([0, 0, 255])
    out_image[rr_p, cc_p, ...] = np.array([255, 0, 0])

    return out_image.astype(np.uint8)
Esempio n. 37
0
def find_plate(path):
    # Load picture, convert to grayscale and detect edges
    image_rgb = io.imread(path)
    image_rgb = rescale(image_rgb, 0.05)
    image_gray = color.rgb2gray(image_rgb)
    edges = canny(image_gray, sigma=2.0, low_threshold=0.2, high_threshold=0.8)

    # Perform a Hough Transform
    # The accuracy corresponds to the bin size of a major axis.
    # The value is chosen in order to get a single high accumulator.
    # The threshold eliminates low accumulators
    result = hough_ellipse(edges)
    # plt.imshow(edges)
    # plt.show()
    # print (0)
    # result = hough_ellipse(edges)
    print(result.size)
    if result.size == 0:
        print(path + "\t non detected")
        return

    print(path + "\t detected")
    result.sort(order='accumulator')

    # Estimated parameters for the ellipse
    best = list(result[-1])
    yc, xc, a, b = [int(round(x)) for x in best[1:5]]
    orientation = best[5]

    # Draw the ellipse on the original image
    cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
    try:
        image_rgb[cy, cx] = (0, 0, 255)
        edges = color.gray2rgb(img_as_ubyte(edges))
        edges[cy, cx] = (250, 0, 0)
    except IndexError as e:
        print(e)
    # Draw the edge (white) and the resulting ellipse (red)

    fig2, (ax1, ax2) = plt.subplots(ncols=2,
                                    nrows=1,
                                    figsize=(8, 4),
                                    sharex=True,
                                    sharey=True)

    ax1.set_title('Original picture')
    ax1.imshow(image_rgb)

    ax2.set_title('Edge (white) and result (red)')
    ax2.imshow(edges)

    plt.show()
Esempio n. 38
0
def intensity(self, size=None, t=None, smoothing_window=None, substract_noise=True):
    """
    Mean intensity at the position of the particle along time.

    Arguments:
        size <int, float, 2-tuple>: radius of the ellipse to consider for intensity, in pixels. Centered at the center of the particle. If None, uses the mean sx and sy values of the particle.
        t <2,3-tuple, slice, int>: the timepoints at which to collect the intensity information. As compatible with cats.utils.slicify. If 'None', uses the whole length of the dataset.
        smoothing_window <int>: The number of datapoints to average to smooth the output
        substract_noise <bool>: Whether to substract the surrounding value of noise from the intensity.
    """
    noise_distance = 2  # Extra diameter to get noise close to content
    T, I = list(), list()

    # Treat time
    ts = slicify(t, slice(0, self.source.length, 1))

    # Treat size
    if size is None:
        sx, sy = int(ceil(np.mean(self.sx))), int(ceil(np.mean(self.sy)))
    elif type(size) in (int, float):
            sx, sy = int(ceil(size)), int(ceil(size))
    elif '__iter__' in dir(size):
        sx, sy = int(ceil(size[0])), int(ceil(size[1]))

    # Get data
    for t in range(ts.start, ts.stop, ts.step):
        # Get the exact or closest position for given time
        if t not in self.t:
            index = np.where(self.t == get_closest_value(t, self.t))[0]
        else:
            index = np.where(self.t == t)[0]

        # Get the xy position and data at exact or closest time
        roi = draw.ellipse(int(self.y[index]), int(self.x[index]), sy, sx, shape=self.source.shape)
        spot = self.source.get(t)[roi]
        intensity = spot.mean()

        # Remove noise
        if substract_noise == True:
            noise = draw.ellipse_perimeter(int(self.y[index]), int(self.x[index]), sy + noise_distance, sx + noise_distance, shape=self.source.shape)
            noise = self.source.get(t)[noise]
            intensity -= noise.mean()

        T.append(t)
        I.append(intensity)

    if smoothing_window is not None and smoothing_window > 1:
        for t in range(0, len(I)):
            j, k = max(t - smoothing_window, 0), min(t + smoothing_window, len(I))
            I[t] = np.median(I[j:k])

    return T, I
Esempio n. 39
0
def detect(d, i,**kwargs):
    image = d.read(d.images[i])
    global rgb
    rgb = d.read(d.images[i], flatten=False)
    pupil = find_pupil(image)[0]
    img, points, ellipse = find_iris(image, pupil, **kwargs)
    x, y = circle_perimeter(pupil[0], pupil[1], pupil[2])
    rgb[x,y] = (220, 40, 40)
    ex, ey = ellipse.center
    major, minor = ellipse.axes
    orientation = ellipse.orientation
    x, y = ellipse_perimeter(int(ex), int(ey), int(major), int(minor), orientation)
    rgb[x,y] = (220, 40, 40)
    imshow(rgb)
def test_hough_ellipse_non_zero_posangle2():
    # ry < rx, angle in [0:pi/2]
    img = np.zeros((30, 24), dtype=int)
    rx = 12
    ry = 6
    x0 = 10
    y0 = 15
    angle = np.pi / 1.35
    rr, cc = ellipse_perimeter(y0, x0, ry, rx, orientation=angle)
    img[rr, cc] = 1
    result = tf.hough_ellipse(img, threshold=15, accuracy=3)
    result.sort(order="accumulator")
    best = result[-1]
    assert_almost_equal(best[1] / 100.0, y0 / 100.0, decimal=1)
    assert_almost_equal(best[2] / 100.0, x0 / 100.0, decimal=1)
    assert_almost_equal(best[3] / 10.0, ry / 10.0, decimal=1)
    assert_almost_equal(best[4] / 100.0, rx / 100.0, decimal=1)
    assert_almost_equal(best[5], angle, decimal=1)
    # Check if I re-draw the ellipse, points are the same!
    # ie check API compatibility between hough_ellipse and ellipse_perimeter
    rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]), orientation=best[5])
    assert_equal(rr, rr2)
    assert_equal(cc, cc2)
Esempio n. 41
0
def draw_ellipses(slice_data, ellipse, color=(220, 20, 20)):
    yc, xc = [int(round(x)) for x in ellipse.centroid]
    orientation = ellipse.orientation
    major_axis = int(round(ellipse.major_axis_length/2.))
    minor_axis = int(round(ellipse.minor_axis_length/2.))

    image = ski.color.gray2rgb(slice_data)

    cy, cx = ellipse_perimeter(yc, xc, minor_axis, major_axis, -orientation)
    image[cy, cx] = color

    rr, cc = circle(yc, xc, 2)
    image[rr, cc] = color

    return image
def test_hough_ellipse_zero_angle():
    img = np.zeros((25, 25), dtype=int)
    a = 6
    b = 8
    x0 = 12
    y0 = 12
    angle = 0
    rr, cc = ellipse_perimeter(x0, x0, b, a)
    img[rr, cc] = 1
    result = tf.hough_ellipse(img, threshold=9)
    assert_equal(result[0][0], x0)
    assert_equal(result[0][1], y0)
    assert_almost_equal(result[0][2], b, decimal=1)
    assert_almost_equal(result[0][3], a, decimal=1)
    assert_equal(result[0][4], angle)
Esempio n. 43
0
 def draw_ellipse(self, i=0):
     data = self._results_flat
     j = _np.argmax(data['count_density'][i])
     x, y = _skdraw.ellipse_perimeter(
         cy          = data['yc'][i][j].astype('int'),
         cx          = data['xc'][i][j].astype('int'),
         yradius     = data['a'][i][j].astype('int'),
         xradius     = data['b'][i][j].astype('int'),
         orientation = data['orientation'][i][j]
         )
     
     bounds_int = self._bounds[i].astype('int')
     
     bounds_int[x, y] = 2
 
     _ss.matplotlib.Imshow_Slider(bounds_int)
Esempio n. 44
0
def main():
    # Load picture, convert to grayscale and detect edges
    camera = cv2.VideoCapture(0)
    (ret, img) = camera.read()
    cv2.imshow("blah",img)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    cp = gray.copy()
    edges = cv2.Canny(gray,50,150,apertureSize = 3)
    print "hi"
    edges = img_as_float(edges)
    print "hi"

    # Perform a Hough Transform
    # The accuracy corresponds to the bin size of a major axis.
    # The value is chosen in order to get a single high accumulator.
    # The threshold eliminates low accumulators
    result = hough_ellipse(edges, accuracy=20, threshold=250, min_size=100, max_size=120)
    print "hi"
    result.sort(order='accumulator')
    print result

    # Estimated parameters for the ellipse
    if (len(result) > 0):
        print "apple"
        best = list(result[-1])
        yc, xc, a, b = [int(round(x)) for x in best[1:5]]
        orientation = best[5]

        # Draw the ellipse on the original image
        cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
        image_rgb[cy, cx] = (0, 0, 255)
        # Draw the edge (white) and the resulting ellipse (red)
        edges = color.gray2rgb(edges)
        edges[cy, cx] = (25, 0, 255)

    # fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True,
    #                                 sharey=True,
    #                                 subplot_kw={'adjustable':'box-forced'})

    # ax1.set_title('Original picture')
    cv2.imshow("apple",img_as_ubyte(edges))
Esempio n. 45
0
def test_ellipse_perimeter_zeroangle():
    # angle == 0
    img = np.zeros((30, 15), "uint8")
    rr, cc = ellipse_perimeter(15, 7, 14, 6, 0)
    img[rr, cc] = 1
    img_ = np.array(
        [
            [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, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
        ]
    )

    assert_array_equal(img, img_)
Esempio n. 46
0
 def redraw():
     global points
     global ellipse_params
     global in_image
     global plt
     global fig
     
     display_image = np.copy(in_image)
     
     from skimage.draw import line
     r_index, c_index = line(points[0][0], points[0][1], points[1][0], points[1][1])
     display_image[r_index, c_index] = np.array([200, 0, 0])
     
     if ellipse_params is not None:
         r_index, c_index = ellipse_perimeter(ellipse_params[0], ellipse_params[1],
                                              ellipse_params[2], ellipse_params[3],
                                              ellipse_params[4])
         display_image[r_index, c_index] = np.array([0, 0, 200])
     
     pltcop.set_data(display_image)
     fig.canvas.draw()
Esempio n. 47
0
def test_detect_by_stats():
    data = np.memmap("E:\\guts_tracking\\data\\fish202_aligned_masked_8bit_150x200x440.raw", dtype='uint8', shape=(440,200,150)).copy()

    data_slice = data[68]

    slice_data = preprocess_data(data_slice)
    labeled_data, num_features = segment_data(slice_data)

    #plt.imshow(labeled_data == 4, cmap='gray')
    #plt.show()

    stats = slice_stats(labeled_data)

    #stats = stats[(stats.area > 20) & (stats.area < np.pi * min(data_slice.shape)**2)]
    #stats = stats[(stats.area > 20) & (stats.area < 20000)]
    stats = stats[(stats.area > 2) & (stats.area < 20000)]
    #print stats
    #stats = stats[stats.circularity > 0.2]

    image = data_slice

    for index, row in stats.iterrows():
        print row
        yc, xc = [int(round(x)) for x in row.centroid]
        orientation = row.orientation
        major_axis = int(round(row.major_axis_length/2.))
        minor_axis = int(round(row.minor_axis_length/2.))

        image = ski.color.gray2rgb(image)

        cy, cx = ellipse_perimeter(yc, xc, minor_axis, major_axis, -orientation)
        image[cy, cx] = (220, 20, 20)

        rr, cc = circle(yc, xc, 2)
        image[rr, cc] = (220, 20, 20)

    plt.imshow(image, cmap='gray')
    plt.show()

    print stats
Esempio n. 48
0
def test_ellipse_perimeter_nzeroangle():
    # angle != 0
    img = np.zeros((30, 25), "uint8")
    rr, cc = ellipse_perimeter(15, 11, 12, 6, 1.1)
    img[rr, cc] = 1
    img_ = np.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, 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, 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, 1, 1, 1, 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, 1, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
            [1, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 1, 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, 1, 1, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        ]
    )
    assert_array_equal(img, img_)
# Perform a Hough Transform
# The accuracy corresponds to the bin size of a major axis.
# The value is chosen in order to get a single high accumulator.
# The threshold eliminates low accumulators
accum = hough_ellipse(edges, accuracy=10, threshold=170, min_size=50)
accum.sort(key=lambda x:x[5])
# Estimated parameters for the ellipse
center_y = int(accum[-1][0])
center_x = int(accum[-1][1])
xradius = int(accum[-1][2])
yradius = int(accum[-1][3])
angle = np.pi - accum[-1][4]

# Draw the ellipse on the original image
cx, cy = ellipse_perimeter(center_y, center_x,
                           yradius, xradius, orientation=angle)
image_rgb[cy, cx] = (0, 0, 1)
# Draw the edge (white) and the resulting ellipse (red)
edges = color.gray2rgb(edges)
edges[cy, cx] = (250, 0, 0)

fig = plt.subplots(figsize=(10, 6))
plt.subplot(1, 2, 1)
plt.title('Original picture')
plt.imshow(image_rgb)
plt.subplot(1, 2, 2)
plt.title('Edge (white) and result (red)')
plt.imshow(edges)

plt.show()
Esempio n. 50
0
def annotate_ellipse(input_image, filename, output_filename, tag, params=None, save=True):
    from skimage.draw import ellipse_perimeter
    import matplotlib.pyplot as plt
    global in_image
    global in_filename
    
    in_image = input_image
    in_filename = filename
    display_image = np.copy(input_image)
    
    if params:
        r_index, c_index = ellipse_perimeter(params[0], params[1],
                                                 params[2], params[3],
                                                 float(params[4]))
        display_image[r_index, c_index] = np.array([0, 0, 200])
    
    
    
    
    global fig
    global plt
    
    fig, ax = plt.subplots(1, 1)
    fig.set_size_inches(8, 4, forward=True)
    plt.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)
    pltcop = ax.imshow(display_image)
    ax.set_xticks(())
    ax.set_yticks(())
    
    global click_counter
    global is_select_axis
    global points
    global semi_minor
    global ellipse_params
    
    click_counter = 0
    points = [[0, 0], [0, 0]]
    is_select_axis = True
    semi_minor = 5
    ellipse_params = [0, 0, 0, 0, 0]
    
        
    def redraw():
        global points
        global ellipse_params
        global in_image
        global plt
        global fig
        
        display_image = np.copy(in_image)
        
        from skimage.draw import line
        r_index, c_index = line(points[0][0], points[0][1], points[1][0], points[1][1])
        display_image[r_index, c_index] = np.array([200, 0, 0])
        
        if ellipse_params is not None:
            r_index, c_index = ellipse_perimeter(ellipse_params[0], ellipse_params[1],
                                                 ellipse_params[2], ellipse_params[3],
                                                 ellipse_params[4])
            display_image[r_index, c_index] = np.array([0, 0, 200])
        
        pltcop.set_data(display_image)
        fig.canvas.draw()
    
    def click(event):
        global click_counter
        global points
        global is_select_axis
        global semi_minor
        global ellipse_params
        
        def find_length(y1, y2, x1, x2):
            from math import sqrt, pow
            return sqrt(pow(y1 - y2, 2) + pow(x1 - x2, 2))
        def find_center(y1, y2, x1, x2):
            return [(y1 + y2) / 2, (x1 + x2) / 2]
        def find_rad(y1, y2, x1, x2):
            from math import radians
            if x1 == x2: return radians(90)
            else:
                return float(y1 - y2) / float(x1 - x2)
                
        if event.button == 3:
            is_select_axis = not is_select_axis
        
        elif event.button == 1:
            if(event.xdata is None): return
            
            x = int(event.xdata)
            y = int(event.ydata)
            if is_select_axis:
                points[click_counter] = [y, x]
                click_counter += 1
                if click_counter >= len(points):
                    click_counter = 0  
            
            center_y, center_x = find_center(points[0][0], points[1][0], points[0][1], points[1][1])
            if not is_select_axis:
                semi_minor = find_length(center_y, y, center_x, x)
            semi_major = find_length(points[0][0], points[1][0], points[0][1], points[1][1]) / 2
            from math import atan
            radi = atan(find_rad(points[0][0], points[1][0], points[0][1], points[1][1]))
            ellipse_params = [int(center_y), int(center_x), int(semi_minor), int(semi_major), radi]
            redraw()
    
    def on_key(event):
        global points
        global ellipse_params
        global in_filename
        if event.key == "enter" or event.key == "shift":
            if save:
                f = open(combined_dir + output_filename , 'a')
                f.write(in_filename + ",")
                for e_param in ellipse_params:
                    f.write(str(e_param) + ",")
                f.write(tag + "\n")
                f.close()
                print "%s:%s" % (in_filename, str(ellipse_params))
            plt.close('all')
    
    if params:
        cid = fig.canvas.mpl_connect('button_press_event', click)
        cid = fig.canvas.mpl_connect('key_press_event', on_key)

    mng = plt.get_current_fig_manager()
    mng.resize(*mng.window.maxsize())
    plt.show()
Esempio n. 51
0
              low_threshold=0.55, high_threshold=0.8)
# Perform a Hough Transform
# The accuracy corresponds to the bin size of a major axis.
# The value is chosen in order to get a single high accumulator.
# The threshold eliminates low accumulators
result = hough_ellipse(edges, accuracy=20, threshold=250,
                       min_size=100, max_size=120)
result.sort(order='accumulator')

# Estimated parameters for the ellipse
best = list(result[-1])
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]

# Draw the ellipse on the original image
cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
image_rgb[cy, cx] = (0, 0, 255)
# Draw the edge (white) and the resulting ellipse (red)
edges = color.gray2rgb(edges)
edges[cy, cx] = (250, 0, 0)

fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True,
                                sharey=True,
                                subplot_kw={'adjustable':'box-forced'})

ax1.set_title('Original picture')
ax1.imshow(image_rgb)

ax2.set_title('Edge (white) and result (red)')
ax2.imshow(edges)
Esempio n. 52
0
import random
import imp
ksvd = imp.load_source('ksvd', '../Source/ksvd.py')
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import orthogonal_mp
from skimage.draw import circle_perimeter, ellipse_perimeter, polygon, line

################# COLLECTION OF SHAPES #######################

cercle = np.zeros((10, 10), np.uint8)
cercle[circle_perimeter(4, 4, 3)] = 1

ellipse = np.zeros((10, 10), np.uint8)
ellipse[ellipse_perimeter(4, 4, 3, 5)] = 1

square = np.zeros((10, 10), np.uint8)
square[polygon(np.array([1, 4, 4, 1]), np.array([1, 1, 4, 4]))] = 1

dline = np.zeros((10, 10), np.uint8)
dline[line(1, 1, 8, 8)] = 1

shapes = [cercle, ellipse, square, dline]


################ GENERATING DICTIONARY ####################

D = np.zeros((100, 4))

for i in range(len(shapes)):
Esempio n. 53
0
    (480, 320),
    (380, 430),
    (220, 590),
    (300, 300),
))
rr, cc = polygon(poly[:,0], poly[:,1], img.shape)
img[rr,cc,1] = 255

# fill circle
rr, cc = circle(200, 200, 100, img.shape)
img[rr,cc,:] = (255, 255, 0)

# fill ellipse
rr, cc = ellipse(300, 300, 100, 200, img.shape)
img[rr,cc,2] = 255

# circle
rr, cc = circle_perimeter(120, 400, 15)
img[rr, cc, :] = (255, 0, 0)

# ellipses
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 4.)
img[rr, cc, :] = (255, 0, 255)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=-math.pi / 4.)
img[rr, cc, :] = (0, 0, 255)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 2.)
img[rr, cc, :] = (255, 255, 255)

plt.imshow(img)
plt.show()