def polygon(self, npoints = all):
   """Returns polygon for the worm outline
   
   Arguments:
     npoints (int or all): number of points along one side of the worm
   
   Returns:
     array (2xm): reference points on the polygon
   """
   
   left, right = self.shape();
   poly = np.vstack([left, right[::-1,:]]);
   
   if npoints is not all:
     poly = resample_curve(poly, npoints);
   
   return poly;
Example #2
0
    def polygon(self, npoints=all):
        """Returns polygon for the worm outline
    
    Arguments:
      npoints (int or all): number of points along one side of the worm
    
    Returns:
      array (2xm): reference points on the polygon
    """

        left, right = self.shape()
        poly = np.vstack([left, right[::-1, :]])

        if npoints is not all:
            poly = resample_curve(poly, npoints)

        return poly
Example #3
0
img = exp.load_img(wid=80, t=t0)
#imgs = filters.gaussian_filter(np.asarray(img, float), 1.0);

w = wm.WormModel(npoints=10)
w.from_image(img, verbose=False)

w.move_forward(0.1)
w.rotate(0.1)

contours = wgeo.contours_from_image(img,
                                    sigma=1,
                                    absolute_threshold=None,
                                    threshold_factor=0.9,
                                    verbose=False,
                                    save=None)
contour = Curve(resample_curve(contours[0], 100), nparameter=50)

head_tail_xy = wgeo.head_tail_from_contour_discrete(contour,
                                                    ncontour=all,
                                                    delta=0.3,
                                                    smooth=1.0,
                                                    with_index=False,
                                                    verbose=True,
                                                    save=None,
                                                    image=imgs)

plt.figure(1)
plt.clf()
w.plot(image=img)
contour.plot(with_points=False)
 worm.from_image(img, absolute_threshold = absolute_threshold, threshold_factor = threshold_factor, verbose = True);
 worm0 = worm.copy();
 
 plt.figure(1); 
 plt.subplot(2,3,2)
 worm0.plot(image = imgs)
 worm0.plot()
 
 
 ### Initialize Contour to match the worm to from another image
 img2 = exp.load_img(wid = 80, t = t0+10);
 
 plt.figure(2); plt.clf();
 cntrs = wgeo.contour_from_image(img2, sigma = 1, absolute_threshold = absolute_threshold, threshold_factor = threshold_factor, 
                                 verbose = True, save = None);
 cntr = resample_curve(cntrs[0], 100); #assume outer contour is first, only match to this
 contour = Curve(cntr, nparameter = 50);
 
 plt.figure(3); plt.clf();
 worm0.plot(image = img2);
 contour.plot();
                       
 ### Detect Head/Tail candidates
 plt.figure(3); plt.clf();
 match_head_tail = wgeo.head_tail_from_contour(cntrs, ncontour = all, delta = 0.3, smooth = 1.0, with_index = False,
                                               verbose = True, save = None, image = img2);
 
 
 #plt.figure(21); plt.clf();
 #plt.subplot(1,2,1)
 #dist = worm0.distance_to_contour(contour, verbose = True);
Example #5
0
    plt.subplot(2, 3, 2)
    worm0.plot(image=imgs)
    worm0.plot()

    ### Initialize Contour to match the worm to from another image
    img2 = exp.load_img(wid=80, t=t0 + 10)

    plt.figure(2)
    plt.clf()
    cntrs = wgeo.contour_from_image(img2,
                                    sigma=1,
                                    absolute_threshold=absolute_threshold,
                                    threshold_factor=threshold_factor,
                                    verbose=True,
                                    save=None)
    cntr = resample_curve(cntrs[0], 100)
    #assume outer contour is first, only match to this
    contour = Curve(cntr, nparameter=50)

    plt.figure(3)
    plt.clf()
    worm0.plot(image=img2)
    contour.plot()

    ### Detect Head/Tail candidates
    plt.figure(3)
    plt.clf()
    match_head_tail = wgeo.head_tail_from_contour(cntrs,
                                                  ncontour=all,
                                                  delta=0.3,
                                                  smooth=1.0,
imgs = filters.gaussian_filter(np.asarray(img, float), 1.0);

w = wm.WormModel(npoints = 20);  
w.from_image(img, verbose = True);

w.move_forward(0.1);
w.rotate(0.1);


plt.figure(1); plt.clf();
plt.subplot(1,2,1)
w.plot(image = imgs)
plt.subplot(1,2,2);
cntrs = wgeo.contour_from_image(imgs, sigma = 1, absolute_threshold = None, threshold_factor = 0.9, 
                          verbose = True, save = None);
cntr = resample_curve(cntrs[0], 100);
contour = Curve(cntr, nparameter = 50);                        
                      
                      
plt.figure(2); plt.clf();
head_tail_xy = wgeo.head_tail_from_contour(cntrs, ncontour = all, delta = 0.3, smooth = 1.0, with_index = False,
                            verbose = True, save = None, image = imgs);


left,right,normals = w.shape(with_normals=True);  
plt.figure(3); plt.clf()
reload(wgeo)
res = wgeo.distance_shape_to_contour_discrete(left,right,normals,contour,
                                              search_radius=[5,20], min_alignment=0, match_head_tail=head_tail_xy,
                                              verbose = True);
 

w = wm.WormModel(npoints = 15);  
plt.figure(1); plt.clf();
w.from_image(img, verbose = True, nneighbours=1);

plt.figure(2); plt.clf();
w.plot(image = img);

w.move_forward(0.1);
w.rotate(0.1);


contours = wgeo.contours_from_image(imgs, sigma = 1, absolute_threshold = None, threshold_factor = 0.9, 
                                verbose = False, save = None);
contour = Curve(resample_curve(contours[0], 100), nparameter = 50);                                   

head_tail_xy = wgeo.head_tail_from_contour_discrete(contour, ncontour = all, delta = 0.3, smooth = 1.0, with_index = False,
                            verbose = True, save = None, image = imgs);

plt.figure(1); plt.clf();
w.plot(image = imgs)
contour.plot(with_points=False);

par = w.get_parameter()
npar = par.shape[0]

eps = 0.1 * np.ones(npar);
ik = w.center.shape[0];
eps[:ik] = 0.5;
def center_from_sides_min_projection(left, right, npoints = all, nsamples = all, resample = False, with_width = False, smooth = 0, center_offset = 2, iterations = 3, verbose = False):
  """Finds middle line between the two side curves using projection method with minimal  advancements
  
  Arguments:
    left, right (nx2 array): vertices of the left and right curves
    npoints (int or all): number of points of the mid line
    nsamples (int or all): number of sample points to contruct midline
    with_width (bool): if True also return estimated width
    nneighbours (int or all): number of neighbouring points to include for projection
  
  Returns:
    nx2 array of midline vertices
  """
  
  # resample to same size
  nl = left.shape[0];
  nr = right.shape[0];
  if nsamples is all:
    nsamples = max(nl,nr);
  if npoints is all:
    npoints = max(nl,nr);
  
  if nl != nsamples or nr != nsamples or resample:
    leftcurve  = resample_curve(left, nsamples);
    rightcurve = resample_curve(right, nsamples);
  else:
    leftcurve = left;
    rightcurve = right;
    
  #plt.scatter(*leftcurve.T, c = 'w', s = 80);
  #plt.scatter(*rightcurve.T, c = 'w', s = 80);
  #plt.scatter(*rightcurve[0], c = 'm', s = 80);
  #plt.scatter(*leftcurve[0], c = 'b', s = 80);
  #print leftcurve.shape
  #print rightcurve.shape
  #return;
  
  #head tail always include as first last data point
  center_offset += 1;  
  
  # calculate center
  full_left = [leftcurve[i] for i in range(center_offset)];
  full_right = [rightcurve[i] for i in range(center_offset)];
  
  il = center_offset-1; ir = center_offset-1;
  leftline  = geom.LineString( leftcurve[ir:ir+2]); 
  rightline = geom.LineString(rightcurve[il:il+2]);
  
  il = center_offset; ir = center_offset;
  left_point  = geom.Point(leftcurve[il,0], leftcurve[il,1]);
  right_point = geom.Point(rightcurve[ir,0], rightcurve[ir,1]); 
  
  while il < nsamples-center_offset and ir < nsamples-center_offset:
    #print il,ir
    ul = leftline.project(right_point, normalized = True);
    ur = rightline.project(left_point, normalized = True);
    #print ul,ur
    #print left_point, right_point
    #print (il, ir, ul, ur)
    #print left_point.coords[0], leftcurve[il-1],  leftcurve[il]
    if ul == ur:
      l0 = leftcurve[il - 1]; l1 = leftcurve[il];
      r0 = rightcurve[ir - 1]; r1 = rightcurve[ir];
      q = np.argmin(np.linalg.norm([r0-l1, r1-l0, r1-l1], axis = 1));
      #print q, np.linalg.norm([r0-l1, r1-l0, r1-l1], axis = 1)
      
      if q == 0: #progress on left
        full_left.append(l1);
        full_right.append(r0);
        leftline = geom.LineString(leftcurve[il:il+2]);
        il+=1;
        left_point = geom.Point(leftcurve[il,0], leftcurve[il,1]);
      elif q ==1: # progress on right
        full_left.append(l0);
        full_right.append(r1);
        rightline = geom.LineString(rightcurve[ir:ir+2]);
        ir+=1;
        right_point = geom.Point(rightcurve[ir,0], rightcurve[ir,1]);
      else: # progress both
        full_left.append(left_point.coords[0]);
        full_right.append(right_point.coords[0]);
        leftline = geom.LineString(leftcurve[il:il+2]);
        rightline = geom.LineString(rightcurve[ir:ir+2]);
        il+=1;
        ir+=1;
        left_point = geom.Point(leftcurve[il,0], leftcurve[il,1]);
        right_point = geom.Point(rightcurve[ir,0], rightcurve[ir,1]);
    elif ul < ur: # add center from right
      full_left.append(leftline.interpolate(ul, normalized = True).coords[0]);
      full_right.append(right_point.coords[0]);
      rightline = geom.LineString(rightcurve[ir:ir+2]);
      ir+=1;
      right_point = geom.Point(rightcurve[ir,0], rightcurve[ir,1]);
    else:
      full_left.append(left_point.coords[0]);
      full_right.append(rightline.interpolate(ur, normalized = True).coords[0]);
      leftline = geom.LineString(leftcurve[il:il+2]);
      il+=1;
      left_point = geom.Point(leftcurve[il,0], leftcurve[il,1]);
  
  if il < ir:
    for i in range(il, nsamples-center_offset):
      full_left.append(leftcurve[i]);
      full_right.append(rightcurve[ir]);
  elif ir < il:
    for i in range(ir, nsamples-center_offset):
      full_left.append(leftcurve[il]);
      full_right.append(rightcurve[i]);
  
  
  full_left.extend([leftcurve[i] for i in range(-center_offset,0)]);
  full_right.extend([rightcurve[i] for i in range(-center_offset,0)]);
  
  full_left = np.array(full_left);
  full_right = np.array(full_right);
  
  #print full_left
  #print full_right
  center = (full_left + full_right)/2.0;
  center = resample_nd(center, npoints, smooth = smooth, iterations = 1);
  center = resample_nd(center, npoints, smooth = 0, iterations = 2); # homogenize distances between points
  
  #print center
  if verbose:
    plt.plot(*leftcurve.T, c = 'r');
    plt.plot(*rightcurve.T, c = 'b');
    for xy1,xy2 in zip(full_left, full_right):
      plt.plot([xy1[0], xy2[0]], [xy1[1], xy2[1]], c = 'g');
    #plt.scatter(*full_left[0], c = 'm', s = 50);
    plt.scatter(*leftcurve.T, c = np.arange(len(leftcurve)), s=  50);
    plt.scatter(*rightcurve.T, c = np.arange(len(leftcurve)), s = 50);

    
  
  if not with_width:
    return center;
  else:
    width = np.linalg.norm(full_left-full_right, axis = 1);
    width = 0.5 * resample_curve(width, npoints, smooth = 0);
    
    #lc = np.asarray(leftcurve, dtype = 'float32');
    #rc = np.asarray(rightcurve, dtype = 'float32');
    #cnt = np.vstack(lc, rc[::-1]);
    #width_l = np.array([np.min(np.linalg.norm(leftcurve - c, axis = 1)) for c in center])  
    #width_r = np.array([np.min(np.linalg.norm(rightcurve - c, axis = 1)) for c in center])  
    
    #width_l = np.array([cv2.pointPolygonTest(lc,(c[0],c[1]),True) for c in center]);
    #width_r = np.array([cv2.pointPolygonTest(rc,(c[0],c[1]),True) for c in center]);
    #width = (width_l + width_r); 
    #width = 2* np.min([width_l, width_r], axis = 0);
    #width[[0,-1]] = 0.0;
  
    return center, width
def center_from_sides_min_projection(left,
                                     right,
                                     npoints=all,
                                     nsamples=all,
                                     resample=False,
                                     with_width=False,
                                     smooth=0,
                                     center_offset=2,
                                     iterations=3,
                                     verbose=False):
    """Finds middle line between the two side curves using projection method with minimal  advancements
  
  Arguments:
    left, right (nx2 array): vertices of the left and right curves
    npoints (int or all): number of points of the mid line
    nsamples (int or all): number of sample points to contruct midline
    with_width (bool): if True also return estimated width
    nneighbours (int or all): number of neighbouring points to include for projection
  
  Returns:
    nx2 array of midline vertices
  """

    # resample to same size
    nl = left.shape[0]
    nr = right.shape[0]
    if nsamples is all:
        nsamples = max(nl, nr)
    if npoints is all:
        npoints = max(nl, nr)

    if nl != nsamples or nr != nsamples or resample:
        leftcurve = resample_curve(left, nsamples)
        rightcurve = resample_curve(right, nsamples)
    else:
        leftcurve = left
        rightcurve = right

    #plt.scatter(*leftcurve.T, c = 'w', s = 80);
    #plt.scatter(*rightcurve.T, c = 'w', s = 80);
    #plt.scatter(*rightcurve[0], c = 'm', s = 80);
    #plt.scatter(*leftcurve[0], c = 'b', s = 80);
    #print leftcurve.shape
    #print rightcurve.shape
    #return;

    #head tail always include as first last data point
    center_offset += 1

    # calculate center
    full_left = [leftcurve[i] for i in range(center_offset)]
    full_right = [rightcurve[i] for i in range(center_offset)]

    il = center_offset - 1
    ir = center_offset - 1
    leftline = geom.LineString(leftcurve[ir:ir + 2])
    rightline = geom.LineString(rightcurve[il:il + 2])

    il = center_offset
    ir = center_offset
    left_point = geom.Point(leftcurve[il, 0], leftcurve[il, 1])
    right_point = geom.Point(rightcurve[ir, 0], rightcurve[ir, 1])

    while il < nsamples - center_offset and ir < nsamples - center_offset:
        #print il,ir
        ul = leftline.project(right_point, normalized=True)
        ur = rightline.project(left_point, normalized=True)
        #print ul,ur
        #print left_point, right_point
        #print (il, ir, ul, ur)
        #print left_point.coords[0], leftcurve[il-1],  leftcurve[il]
        if ul == ur:
            l0 = leftcurve[il - 1]
            l1 = leftcurve[il]
            r0 = rightcurve[ir - 1]
            r1 = rightcurve[ir]
            q = np.argmin(np.linalg.norm([r0 - l1, r1 - l0, r1 - l1], axis=1))
            #print q, np.linalg.norm([r0-l1, r1-l0, r1-l1], axis = 1)

            if q == 0:  #progress on left
                full_left.append(l1)
                full_right.append(r0)
                leftline = geom.LineString(leftcurve[il:il + 2])
                il += 1
                left_point = geom.Point(leftcurve[il, 0], leftcurve[il, 1])
            elif q == 1:  # progress on right
                full_left.append(l0)
                full_right.append(r1)
                rightline = geom.LineString(rightcurve[ir:ir + 2])
                ir += 1
                right_point = geom.Point(rightcurve[ir, 0], rightcurve[ir, 1])
            else:  # progress both
                full_left.append(left_point.coords[0])
                full_right.append(right_point.coords[0])
                leftline = geom.LineString(leftcurve[il:il + 2])
                rightline = geom.LineString(rightcurve[ir:ir + 2])
                il += 1
                ir += 1
                left_point = geom.Point(leftcurve[il, 0], leftcurve[il, 1])
                right_point = geom.Point(rightcurve[ir, 0], rightcurve[ir, 1])
        elif ul < ur:  # add center from right
            full_left.append(
                leftline.interpolate(ul, normalized=True).coords[0])
            full_right.append(right_point.coords[0])
            rightline = geom.LineString(rightcurve[ir:ir + 2])
            ir += 1
            right_point = geom.Point(rightcurve[ir, 0], rightcurve[ir, 1])
        else:
            full_left.append(left_point.coords[0])
            full_right.append(
                rightline.interpolate(ur, normalized=True).coords[0])
            leftline = geom.LineString(leftcurve[il:il + 2])
            il += 1
            left_point = geom.Point(leftcurve[il, 0], leftcurve[il, 1])

    if il < ir:
        for i in range(il, nsamples - center_offset):
            full_left.append(leftcurve[i])
            full_right.append(rightcurve[ir])
    elif ir < il:
        for i in range(ir, nsamples - center_offset):
            full_left.append(leftcurve[il])
            full_right.append(rightcurve[i])

    full_left.extend([leftcurve[i] for i in range(-center_offset, 0)])
    full_right.extend([rightcurve[i] for i in range(-center_offset, 0)])

    full_left = np.array(full_left)
    full_right = np.array(full_right)

    #print full_left
    #print full_right
    center = (full_left + full_right) / 2.0
    center = resample_nd(center, npoints, smooth=smooth, iterations=1)
    center = resample_nd(center, npoints, smooth=0, iterations=2)
    # homogenize distances between points

    #print center
    if verbose:
        plt.plot(*leftcurve.T, c='r')
        plt.plot(*rightcurve.T, c='b')
        for xy1, xy2 in zip(full_left, full_right):
            plt.plot([xy1[0], xy2[0]], [xy1[1], xy2[1]], c='g')
        #plt.scatter(*full_left[0], c = 'm', s = 50);
        plt.scatter(*leftcurve.T, c=np.arange(len(leftcurve)), s=50)
        plt.scatter(*rightcurve.T, c=np.arange(len(leftcurve)), s=50)

    if not with_width:
        return center
    else:
        width = np.linalg.norm(full_left - full_right, axis=1)
        width = 0.5 * resample_curve(width, npoints, smooth=0)

        #lc = np.asarray(leftcurve, dtype = 'float32');
        #rc = np.asarray(rightcurve, dtype = 'float32');
        #cnt = np.vstack(lc, rc[::-1]);
        #width_l = np.array([np.min(np.linalg.norm(leftcurve - c, axis = 1)) for c in center])
        #width_r = np.array([np.min(np.linalg.norm(rightcurve - c, axis = 1)) for c in center])

        #width_l = np.array([cv2.pointPolygonTest(lc,(c[0],c[1]),True) for c in center]);
        #width_r = np.array([cv2.pointPolygonTest(rc,(c[0],c[1]),True) for c in center]);
        #width = (width_l + width_r);
        #width = 2* np.min([width_l, width_r], axis = 0);
        #width[[0,-1]] = 0.0;

        return center, width