Esempio n. 1
0
def preprocess_image(image_path):
    files = os.listdir(image_path)
    for f in files:
        image = mpimg.imread(image_path + '/' + f)

        img_gray = rgb2gray(image)
        thresh = threshold_otsu(img_gray)
        binary = img_gray > thresh

        # Step 1: Proprocess original images into binary images
        # otsu thresholding with appropriate nbins number
        thresh = threshold_otsu(img_gray, nbins = 60)
        binary = img_gray > thresh
        binary = resize(binary, (1600, 2000))

        # size of blocks
        block_shape = (10, 10)

        # see astronaut as a matrix of blocks (of shape block_shape)
        view = view_as_blocks(binary, block_shape)

        # collapse the last two dimensions in one
        flatten_view = view.reshape(view.shape[0], view.shape[1], -1)

        # resampling the image by taking either the `mean`,
        # the `max` or the `median` value of each blocks.
        mean_view = np.mean(flatten_view, axis=2)

        image = mean_view
        seed = np.copy(mean_view)
        seed[1:-1, 1:-1] = image.max()
        mask = image

        #  fill holes (i.e. isolated, dark spots) in an image using morphological reconstruction by erosion
        # plt.title("Filled dark spots by morphological reconstruction")
        filled = reconstruction(seed, mask, method='erosion')
        plt.figure()
        plt.axis('off')
        plt.imshow(filled, cmap=cm.Greys_r)
        plt.savefig("./enhanced_image/" + f)

        # Step 2: Label Junctions
        denoised = denoise_wavelet(filled, multichannel=True)

        image = filled
        coords1 = corner_peaks(corner_harris(image), min_distance=5)
        coords_subpix1 = corner_subpix(image, coords1, window_size=13)

        image = denoised
        coords2 = corner_peaks(corner_harris(image), min_distance=5)
        coords_subpix2 = corner_subpix(image, coords2, window_size=13)

        fig, ax = plt.subplots()

        ax.imshow(image, interpolation='nearest', cmap=plt.cm.gray)
        ax.plot(coords_subpix1[:, 1], coords_subpix1[:, 0], '+r', markersize=15)
        ax.plot(coords_subpix2[:, 1], coords_subpix2[:, 0], '+r', markersize=15)
        plt.axis('off')
        plt.savefig("./preprocessed_image/" + f)
Esempio n. 2
0
def test_subpix_no_class():
    img = np.zeros((50, 50))
    subpix = corner_subpix(img, np.array([[25, 25]]))
    assert_array_equal(subpix[0], (np.nan, np.nan))

    img[25, 25] = 1e-10
    corner = peak_local_max(corner_harris(img), num_peaks=1)
    subpix = corner_subpix(img, np.array([[25, 25]]))
    assert_array_equal(subpix[0], (np.nan, np.nan))
Esempio n. 3
0
def test_subpix_no_class():
    img = np.zeros((50, 50))
    subpix = corner_subpix(img, np.array([[25, 25]]))
    assert_array_equal(subpix[0], (np.nan, np.nan))

    img[25, 25] = 1e-10
    corner = peak_local_max(corner_harris(img), num_peaks=1)
    subpix = corner_subpix(img, np.array([[25, 25]]))
    assert_array_equal(subpix[0], (np.nan, np.nan))
Esempio n. 4
0
def extract_corner_harris(patch):
    """ Extract four corner points using harris corner detection algorithm

    """
    # Find corner with harris corner detection
    coords = corner_peaks(corner_harris(patch, k=0.1), min_distance=5)
    coords_subpix = corner_subpix(patch, coords, window_size=13)

    # Find the nearest point for each corner
    dim = patch.shape
    corners = [(0, 0), (dim[0], 0), (dim[0], dim[1]), (0, dim[1])]

    dest_points = [[] for x in range(4)]
    for i in xrange(4):
        dest_points[i] = search_closest_points(corners[i], coords_subpix)

    # Check for error
    try:
        epsilon = 1e-10
        for i in xrange(4):
            for j in xrange(i + 1, 4):
                if calc_distance(dest_points[i], dest_points[j]) < epsilon:
                    print 'Error point'
                    return []
    except TypeError:
        return []

    # Reverse y,x position to x,y
    for i in xrange(4):
        dest_points[i][1], dest_points[i][0] = dest_points[i][0], dest_points[i][1]

    return dest_points
def shi_tomasi_skimage(image, min_distance, num_peaks, **kwargs):
    coords_subpix = np.zeros_like(image)
    cornerness_matrix = sf.corner_peaks(sf.corner_shi_tomasi(image), min_distance=min_distance, num_peaks=num_peaks)
    coords_subpix = sf.corner_subpix(image, cornerness_matrix, window_size = 13, alpha=0.8)
    draw_points(image, cornerness_matrix, coords_subpix)
    print("detected points: ",cornerness_matrix.shape[0])
    return cornerness_matrix, coords_subpix
Esempio n. 6
0
def test_subpix():
    img = np.zeros((50, 50))
    img[:25, :25] = 255
    img[25:, 25:] = 255
    corner = peak_local_max(corner_harris(img), num_peaks=1)
    subpix = corner_subpix(img, corner)
    assert_array_equal(subpix[0], (24.5, 24.5))
def test_subpix_dot():
    img = np.zeros((50, 50))
    img[25, 25] = 255
    corner = peak_local_max(corner_harris(img),
                            min_distance=10, threshold_rel=0, num_peaks=1)
    subpix = corner_subpix(img, corner)
    assert_array_equal(subpix[0], (25, 25))
def harris_skimage(image, min_distance, num_peaks, **kwargs):
    coords_subpix = np.zeros_like(image)
    cornerness_matrix = sf.corner_peaks(sf.corner_harris(image), min_distance=min_distance, num_peaks=num_peaks) # larger distance -> fewer points
    coords_subpix = sf.corner_subpix(image, cornerness_matrix, window_size=13, alpha=0.8) # sub pixel accuracy
    draw_points(image, cornerness_matrix, coords_subpix)
    print("detected points: ",cornerness_matrix.shape[0])
    return cornerness_matrix, coords_subpix
Esempio n. 9
0
def test_subpix_dot():
    img = np.zeros((50, 50))
    img[25, 25] = 255
    corner = peak_local_max(corner_harris(img),
                            min_distance=10, threshold_rel=0, num_peaks=1)
    subpix = corner_subpix(img, corner)
    assert_array_equal(subpix[0], (25, 25))
Esempio n. 10
0
def test_subpix():
    img = np.zeros((50, 50))
    img[:25,:25] = 255
    img[25:,25:] = 255
    corner = peak_local_max(corner_harris(img), num_peaks=1)
    subpix = corner_subpix(img, corner)
    assert_array_equal(subpix[0], (24.5, 24.5))
Esempio n. 11
0
def extract_corner_harris(patch):
    """ Extract four corner points using harris corner detection algorithm

    """
    # Find corner with harris corner detection
    coords = corner_peaks(corner_harris(patch, k=0.1), min_distance=5)
    coords_subpix = corner_subpix(patch, coords, window_size=13)

    # Find the nearest point for each corner
    dim = patch.shape
    corners = [(0, 0), (dim[0], 0), (dim[0], dim[1]), (0, dim[1])]

    dest_points = [[] for x in range(4)]
    for i in xrange(4):
        dest_points[i] = search_closest_points(corners[i], coords_subpix)

    # Check for error
    try:
        epsilon = 1e-10
        for i in xrange(4):
            for j in xrange(i + 1, 4):
                if calc_distance(dest_points[i], dest_points[j]) < epsilon:
                    print 'Error point'
                    return []
    except TypeError:
        return []

    # Reverse y,x position to x,y
    for i in xrange(4):
        dest_points[i][1], dest_points[i][0] = dest_points[i][0], dest_points[
            i][1]

    return dest_points
def kitchen_rosenfeld_skimage(image, threshold_abs_kr, min_distance, num_peaks, **kwargs):
    coords_subpix = np.zeros_like(image)
    cornerness_matrix = sf.corner_peaks(sf.corner_kitchen_rosenfeld(image, mode='constant'), 
                                        min_distance=min_distance, num_peaks=num_peaks,
                                        threshold_abs=threshold_abs_kr,
                                        threshold_rel=0.3)
    coords_subpix = sf.corner_subpix(image, cornerness_matrix, window_size = 13, alpha=0.8)
    print("detected points: ",cornerness_matrix.shape[0])
    draw_points(image, cornerness_matrix)
    return cornerness_matrix, coords_subpix
def foerstner_skimage(image, min_distance, num_peaks, **kwargs):
    w, q = sf.corner_foerstner(image)
    q_min = 0.9
    w_min = 0.1
    foerstner = (q > q_min) * (w > w_min) * w
    cornerness_matrix = sf.corner_peaks(foerstner, min_distance=min_distance, num_peaks=num_peaks)
    coords_subpix = sf.corner_subpix(image, cornerness_matrix, window_size=13,alpha=0.8)
    draw_points(image, cornerness_matrix)
    print("detected points: ",cornerness_matrix.shape[0])
    return cornerness_matrix, coords_subpix
Esempio n. 14
0
def detect_corner(img):
    coords = corner_peaks(corner_harris(img), min_distance=5)
    coords_subpix = corner_subpix(img, coords, window_size=13)

    fig, ax = plt.subplots()
    ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)
    ax.plot(coords[:, 1], coords[:, 0], '.b', markersize=3)
    ax.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15)
    # ax.axis((0, 350, 350, 0))
    plt.show()
Esempio n. 15
0
def point_intere(image_name):

    image=np.load(image_name)
    c_h = corner_harris(image)

    coords = corner_peaks(c_h, min_distance=1)

    coords_subpix = corner_subpix(image, coords, window_size=10)

    return del_dubl(my_round(coords_subpix))
Esempio n. 16
0
def test_subpix_border():
    img = np.zeros((50, 50))
    img[1:25, 1:25] = 255
    img[25:-1, 25:-1] = 255
    corner = corner_peaks(corner_harris(img), threshold_rel=0)
    subpix = corner_subpix(img, corner, window_size=11)
    ref = np.array([[0.52040816, 0.52040816], [0.52040816, 24.47959184],
                    [24.47959184, 0.52040816], [24.5, 24.5],
                    [24.52040816, 48.47959184], [48.47959184, 24.52040816],
                    [48.47959184, 48.47959184]])
    assert_almost_equal(subpix, ref)
Esempio n. 17
0
def test_subpix_edge(dtype):
    img = np.zeros((50, 50), dtype=dtype)
    img[:25, :25] = 255
    img[25:, 25:] = 255
    corner = peak_local_max(corner_harris(img),
                            min_distance=10,
                            threshold_rel=0,
                            num_peaks=1)
    subpix = corner_subpix(img, corner)
    assert subpix.dtype == _supported_float_type(dtype)
    assert_array_equal(subpix[0], (24.5, 24.5))
Esempio n. 18
0
def corners(provider):
    """
    number of corners
    """

    gray = provider.as_gray()

    # TODO custom parameters would give arise to exceptions of mis-matched shapes
    coords = corner_peaks(corner_harris(gray))#, min_distance=5)
    coords_subpix = corner_subpix(gray, coords)#, window_size=13)

    return len(coords_subpix)
Esempio n. 19
0
def checkerboard_error(img, mask, min_corners=4):
    """
    Compute the "distance" between the given part of the image and a
    checkerboard, using a rough estimation based on Harris corners.

    In a checkerboard pattern, the immediate neighborhood of every corner
    should be invariant to rotation by 180 degrees. So, compute all corners and
    their neighborhoods, and build an error from the geometric mean of all
    differences produced by these rotations.
    """
    if img.ndim == 3:
        gray = skimage.color.rgb2gray(img)
    else:
        gray = np.copy(img)

    # Use a harris corner detector to detect the corners in the image.
    coords = corner_peaks(corner_harris(gray), min_distance=5)
    # Refine corners to subpixel accuracy (and then round) to make sure our
    # neighborhoods are centered on the corner as much as possible.
    # is needed later in the error computation).
    coords = np.round(corner_subpix(gray, coords, window_size=5))
    # Remove NaN corners (introduced when the refinement fails).
    coords = coords[np.sum(np.isnan(coords), axis=1) == 0]
    # Cast back to integer type, to be able to use these as image coordinates.
    coords = coords.astype(np.int)

    # Clip points that are near the edges of the mask, as these are probably
    # false detections.
    small_mask = morphology.binary_erosion(mask, iterations=5)
    good_coords = small_mask[coords[:, 0], coords[:, 1]]

    # Skip patterns that can't detect enough corners. Checkerboard patterns
    # should enable easy detection of at least a few corners, and using this
    # metric with a few corners lets rise to edge cases.
    if np.sum(good_coords) < min_corners:
        return np.inf

    scores = []
    # Take 5x5 neighborhoods around each pixel and subtract these
    for c in coords[good_coords]:
        patch = img[c[0] - 2:c[0] + 3, c[1] - 2:c[1] + 3]
        diff = patch - patch[::-1, ::-1]
        if diff.ndim == 3:
            diff = np.linalg.norm(diff, axis=-1)
        else:
            diff = np.abs(diff)
        scores.append(np.mean(diff))

    # Compute the geometric mean carefully to avoid overflows.
    log_scores = np.log(scores)
    return np.exp(np.mean(log_scores))
Esempio n. 20
0
def test_subpix_border():
    img = np.zeros((50, 50))
    img[1:25,1:25] = 255
    img[25:-1,25:-1] = 255
    corner = corner_peaks(corner_harris(img), min_distance=1)
    subpix = corner_subpix(img, corner, window_size=11)
    ref = np.array([[ 0.52040816,  0.52040816],
                    [ 0.52040816, 24.47959184],
                    [24.47959184,  0.52040816],
                    [24.5       , 24.5       ],
                    [24.52040816, 48.47959184],
                    [48.47959184, 24.52040816],
                    [48.47959184, 48.47959184]])
    assert_almost_equal(subpix, ref)
Esempio n. 21
0
def manipulateState(s, coordX,coordY):
    if s is not None and len(s) > 0 and s[0] is not None:
        if type(s[0]) == dict and 'vision' in s[0]:
            vi = s[0]['vision']
            mid = vi[75:75+210, 10:10+160, :]
            square = mid[75+50:75+50+160, 10:10+160, :] 

            grey = rgb2gray(square)
            coords = corner_peaks(corner_harris(grey), num_peaks=20, min_distance=5)
            coords_subpix = corner_subpix(grey, coords)
            num_coords = coords.shape[0]
            coords_array = np.zeros((1344,2))
            coords_array[:num_coords, :]=coords
            return tf.reshape(coords_array, shape=[1, -1]).eval()
    return np.zeros(shape=[1,84*32])
def main(argv):
    image = io.imread(argv[0], True)
    smooth = gaussian(image, sigma=4, mode='reflect')
    binary = image > threshold_otsu(smooth)

    skeleton = skeletonize_3d(invert(binary))

    coords = corner_peaks(corner_harris(binary, k=0.2, sigma=4),
                          min_distance=5)
    coords_subpix = corner_subpix(binary, coords, window_size=13)

    fig, ax = plt.subplots()
    ax.imshow(binary, interpolation='nearest', cmap=plt.cm.gray)
    ax.plot(coords[:, 1], coords[:, 0], '+r', markersize=15)
    # ax.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15)
    ax.axis((0, 600, 600, 0))
    plt.show()
Esempio n. 23
0
 def fast_skimage(self, image, **kwargs):
     coords_subpix = np.zeros_like(image)
     cornerness_matrix = sf.corner_peaks(
         sf.corner_fast(image, 16,
                        0.8), min_distance=1)  # no_of_detected_points*2
     coords_subpix = sf.corner_subpix(image,
                                      cornerness_matrix,
                                      window_size=13,
                                      alpha=kwargs["alpha"])
     display.draw_points(image,
                         cornerness_matrix,
                         '_',
                         self.path[2:-1],
                         method_name=kwargs['method'],
                         name=self.name,
                         sp=coords_subpix)
     return cornerness_matrix, coords_subpix
Esempio n. 24
0
 def shi_tomasi_skimage(self, image, **kwargs):
     coords_subpix = np.zeros_like(image)
     cornerness_matrix = sf.corner_peaks(sf.corner_shi_tomasi(image),
                                         min_distance=1)
     coords_subpix = sf.corner_subpix(image,
                                      cornerness_matrix,
                                      window_size=13,
                                      alpha=kwargs["alpha"])
     display.draw_points(image,
                         cornerness_matrix,
                         '_',
                         self.path[2:-1],
                         method_name=kwargs['method'],
                         name=self.name,
                         sp=coords_subpix)
     print("detected points: ", cornerness_matrix.shape[0])
     return cornerness_matrix, coords_subpix
def main(inputfilename, oututfilename):
    # Load image
    image = imread(inputfilename)
    image = rgb2gray(image)

    # Apply corner detection algorithm
    corners = corner_harris(image)
    coords = corner_peaks(corners, min_distance=5)
    coords_subpix = corner_subpix(image, coords, window_size=13)

    # Diplay the image
    fig, ax = plt.subplots()
    ax.imshow(image, interpolation='nearest', cmap=plt.cm.gray)
    ax.plot(coords[:, 1], coords[:, 0], '.b', markersize=3)
    ax.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15)
    ax.axis((0, 350, 350, 0))
    plt.savefig(oututfilename)
Esempio n. 26
0
 def harris_skimage(self, image, num_peaks, **kwargs):
     coords_subpix = np.zeros_like(image)
     cornerness_matrix = sf.corner_peaks(
         sf.corner_harris(image), min_distance=1,
         num_peaks=num_peaks)  # larger distance -> fewer points
     coords_subpix = sf.corner_subpix(
         image, cornerness_matrix, window_size=13,
         alpha=kwargs["alpha"])  # sub pixel accuracy
     display.draw_points(image,
                         cornerness_matrix,
                         '_',
                         self.path[2:-1],
                         method_name=kwargs['method'],
                         name=self.name,
                         sp=coords_subpix,
                         counter=kwargs["counter"])
     print("detected points: ", cornerness_matrix.shape[0])
     return cornerness_matrix, coords_subpix
Esempio n. 27
0
def forward(ob):
    """ 
  Takes raw (768,1024,3) uint8 screen and returns list of VNC events.
  The browser window indents the origin of MiniWob 
  by 75 pixels from top and
  10 pixels from the left. 
  The first 50 pixels along height are the query.
  """
    if ob is None: return []

    x = ob['vision']
    crop = x[75:75 + 50 + 160, 10:10 + 160, :]  # miniwob coordinates crop
    square = x[75 + 50:75 + 50 + 160, 10:10 + 160, :]
    gray = rgb2gray(square)
    print gray
    coords = corner_peaks(corner_harris(gray), min_distance=5)
    coords_subpix = corner_subpix(gray, coords, window_size=13)
    for item in coords_subpix:
        pass
        #print item[0]+75+50,item[1]+10
    newy = coords_subpix[:, 0]
    newx = coords_subpix[:, 1]
    newy = newy[np.logical_not(np.isnan(newy))]
    newx = newx[np.logical_not(np.isnan(newx))]
    #if newx == None or newy == None:
    #return []

    goal_y, goal_x = np.mean(newy) + 125, np.mean(newx) + 10
    if math.isnan(goal_y) or math.isnan(goal_x):
        return []

    print goal_y, goal_x
    #xcoord = np.random.randint(0, 160) + 10         # todo: something more clever here
    #ycoord = np.random.randint(0, 160) + 75 + 50    # todo: something more clever here
    #print ycoord,xcoord
    # 1. move to x,y with left button released, and click there (2. and 3.)
    action = [
        universe.spaces.PointerEvent(goal_x, goal_y, 0),
        universe.spaces.PointerEvent(goal_x, goal_y, 1),
        universe.spaces.PointerEvent(goal_x, goal_y, 0)
    ]

    return action
Esempio n. 28
0
 def kitchen_rosenfeld_skimage(self, image, threshold_abs_kr, **kwargs):
     coords_subpix = np.zeros_like(image)
     cornerness_matrix = sf.corner_peaks(sf.corner_kitchen_rosenfeld(
         image, mode='constant'),
                                         min_distance=1,
                                         threshold_abs=threshold_abs_kr,
                                         threshold_rel=0.3)
     coords_subpix = sf.corner_subpix(image,
                                      cornerness_matrix,
                                      window_size=13,
                                      alpha=kwargs["alpha"])
     display.draw_points(image,
                         cornerness_matrix,
                         '_',
                         self.path[2:-1],
                         method_name=kwargs['method'],
                         name=self.name,
                         sp=coords_subpix)
     print("detected points: ", cornerness_matrix.shape[0])
     return cornerness_matrix, coords_subpix
Esempio n. 29
0
    def show_features(self, gd_file):
        r_img = self.cp.resize_img(PIL.Image.open(gd_file),
                                   base_width=g_prisma_image_size,
                                   keep_size=False)
        l_img = np.float32(r_img.convert('L'))
        ll_img = np.float32(l_img / 255)

        coords = corner_peaks(corner_harris(ll_img), min_distance=5)
        coords_subpix = corner_subpix(ll_img, coords, window_size=25)

        plt.figure(figsize=(8, 8))
        plt.imshow(r_img, interpolation='nearest')
        plt.plot(coords_subpix[:, 1],
                 coords_subpix[:, 0],
                 '+r',
                 markersize=15,
                 mew=5)
        plt.plot(coords[:, 1], coords[:, 0], '.b', markersize=7)
        plt.axis('off')
        plt.show()
Esempio n. 30
0
def centre_button(ob):

  if ob is None: 
    return -1,-1
  x = ob['vision']
  crop = x[75:75+50+160, 10:10+160, :]               # miniwob coordinates crop
  square = x[75+50:75+50+160, 10:10+160, :]  
  gray =rgb2gray(square)
  coords = corner_peaks(corner_harris(gray), min_distance=5)
  coords_subpix = corner_subpix(gray, coords, window_size=13)
  newy = coords_subpix[:,0]
  newx = coords_subpix[:,1]
  newy = newy[np.logical_not(np.isnan(newy))]
  newx = newx[np.logical_not(np.isnan(newx))]

  goal_y,goal_x = np.mean(newy)+125,np.mean(newx)+10
  if math.isnan(goal_y) or math.isnan(goal_x) or goal_y ==None:
    return -1,-1
  
  return goal_y,goal_x
Esempio n. 31
0
 def foerstner_skimage(self, image, num_peaks, **kwargs):
     w, q = sf.corner_foerstner(image)
     q_min = 0.9
     w_min = 0.1
     foerstner = (q > q_min) * (w > w_min) * w
     cornerness_matrix = sf.corner_peaks(foerstner,
                                         min_distance=1,
                                         num_peaks=num_peaks)
     coords_subpix = sf.corner_subpix(image,
                                      cornerness_matrix,
                                      window_size=13,
                                      alpha=kwargs["alpha"])
     display.draw_points(image,
                         cornerness_matrix,
                         '_',
                         self.path[2:-1],
                         method_name=kwargs['method'],
                         name=self.name,
                         sp=coords_subpix)
     print("detected points: ", cornerness_matrix.shape[0])
     return cornerness_matrix, coords_subpix
def rotate_and_crop_image(img_path):
    # open the image
    img = Image.open(img_path)
    date = re.findall(r'(\d\d\d\d-\d\d-\d\d_\d\d-\d\d)', img_path)[0]
    imgNr = re.findall(r'(image\d).jpg', img_path)[0]

    # rotate
    img = img.rotate(272 - 180, resample=Image.BICUBIC,
                     expand=True)  # rotate image

    # crop
    # box = (815, 1345, 920, 1380)
    box = (815 - 100, 1345 - 100, 920 + 100, 1380 + 100)
    img = img.crop(box)

    # save rotated and cropped
    saveDir = "{}/{}/cropped/".format(path_cropped_digits, date)
    if not os.path.exists(saveDir):
        os.makedirs(saveDir)
    save_path_img_rotated = '{}/{}.png'.format(saveDir, imgNr)
    img.save(save_path_img_rotated)

    # load into skimage
    im = io.imread(save_path_img_rotated, as_grey=True)
    #canny filtering
    # c1 = feature.canny(im, sigma=3)
    c2 = feature.canny(im, sigma=5)

    # corner detection
    coords = corner_peaks(corner_harris(c2), min_distance=25)
    coords_subpix = corner_subpix(c2, coords, window_size=13)

    fig, ax = plt.subplots()
    ax.imshow(c2, interpolation='nearest', cmap=plt.cm.gray)
    ax.plot(coords[:, 1], coords[:, 0], '.b', markersize=3)
    ax.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15)
    # ax.axis((0, 350, 350, 0))
    plt.show()
    sys.exit()
Esempio n. 33
0
    def find_corners(self, image, min_distance, window_size):
        """
        :param image:
        :param min_distance:
        :param window_size:
        :return: Points identified as corners.
        """

        # Locate corners, returned values are row/col coordinates (rcs).
        corner_rcs = corner_peaks(corner_harris(image), min_distance)
        subpix_rcs = corner_subpix(image=image,
                                   corners=corner_rcs,
                                   window_size=window_size)

        corners = []
        for i, subpix_rc in enumerate(subpix_rcs):
            if np.isnan(subpix_rc).any():
                corners.append((corner_rcs[i][1], corner_rcs[i][0]))
            else:
                corners.append((subpix_rc[1], subpix_rc[0]))

        return tuple(corners)
Esempio n. 34
0
def getCenterOfButton(s, prevX, prevY, cursorH, cursorW):
    # TODO: check for RGB image
    coords = corner_peaks(corner_harris(s), min_distance=2, threshold_rel=0.01)
    coords_subpix = corner_subpix(s, coords, window_size=13)

    #print 'coords_subpix'
    for item in coords_subpix:
        #print '  ', item[0],item[1],
        if abs(item[0]+125 - prevY) < cursorH and abs(item[1]+10 - prevX) < cursorW:
            #print 'CURSOR',
            item[0] = np.nan
            item[1] = np.nan
        #print ''
    #print '--'

    newX = coords_subpix[:,1]
    newY = coords_subpix[:,0]
    newX = newX[np.logical_not(np.isnan(newX))]
    newY = newY[np.logical_not(np.isnan(newY))]

    goalX = np.mean(newX) + 10
    goalY = np.mean(newY) + 125
    return goalX, goalY, newX, newY
Esempio n. 35
0
def cv_engine(img, operation):
    if operation == 'to_grayscale':
        return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    elif operation == 'get_edge_canny':
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        canny_edges = cv2.Canny(gray, 100, 200, 3)
        return canny_edges
    elif operation == 'get_edge_sobel':
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        x_edges = cv2.Sobel(gray, -1, 1, 0, ksize=5)
        y_edges = cv2.Sobel(gray, -1, 0, 1, ksize=5)
        edges = cv2.addWeighted(x_edges, 0.5, y_edges, 0.5, 0)
        return edges
    elif operation == 'get_corners':
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        from skimage.feature import corner_harris, corner_subpix, corner_peaks
        from skimage import img_as_float
        from skimage.draw import circle
        import math
        # 해리스코너 계산
        image = img_as_float(gray)
        corners = corner_harris(image)
        # 코너 응답을 가지고 이미지에서 실제 코너 계산
        coords = corner_peaks(corners, min_distance=5)
        # 코너가 에지 점인지 독립된 코너인지 결정
        coords_subpix = corner_subpix(image, coords, window_size=13)
        image_corner = np.copy(image)
        for corner in coords_subpix:
            if math.isnan(corner[0]) or math.isnan(corner[1]):
                continue
            corner = [int(x) for x in corner]
            rr, cc = circle(corner[0], corner[1], 5)
            image_corner[rr, cc] = 255  # 이 점을 흰색으로
        image = image * 255 + image_corner
        return image
    else:
        return None
Esempio n. 36
0
def corner_extraction(img_bin, axis_x, axis_y):

    ## Mask
    down_bound = axis_x[0][1]
    left_bound = axis_y[0][0]
    img = np.zeros_like(img_bin)
    pad_size = 2
    img[:down_bound - pad_size, left_bound + pad_size:] = img_bin[:down_bound - pad_size, left_bound + pad_size:]

    corners = corner_peaks(corner_harris(img, k=0.05), min_distance=20)
    corners = corner_process(corners)
    coords_subpix = corner_subpix(img, corners, window_size=13)

    # fig, ax = plt.subplots(figsize=(10, 6), sharex=True, sharey=True)
    # ax.imshow(img, cmap=cm.gray)
    # ax.set_title('Corner Detection')
    # ax.plot(corners[:, 1], corners[:, 0], '.b', markersize=10)
    # ax.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15)
    # ax.set_axis_off()
    # plt.savefig('corner_plot.png')
    # plt.tight_layout()
    # plt.show()

    return corners
Esempio n. 37
0
img_orig = rescale_intensity(img_orig)
img_orig_gray = rgb2gray(img_orig)

# warp synthetic image
tform = AffineTransform(scale=(0.9, 0.9), rotation=0.2, translation=(20, -10))
img_warped = warp(img_orig, tform.inverse, output_shape=(200, 200))
img_warped_gray = rgb2gray(img_warped)

# extract corners using Harris' corner measure
coords_orig = corner_peaks(corner_harris(img_orig_gray), threshold_rel=0.001,
                           min_distance=5)
coords_warped = corner_peaks(corner_harris(img_warped_gray),
                             threshold_rel=0.001, min_distance=5)

# determine sub-pixel corner position
coords_orig_subpix = corner_subpix(img_orig_gray, coords_orig, window_size=10)
coords_warped_subpix = corner_subpix(img_warped_gray, coords_warped,
                                     window_size=10)


def gaussian_weights(window_ext, sigma=1):
    y, x = np.mgrid[-window_ext:window_ext+1, -window_ext:window_ext+1]
    g = np.zeros(y.shape, dtype=np.double)
    g[:] = np.exp(-0.5 * (x**2 / sigma**2 + y**2 / sigma**2))
    g /= 2 * np.pi * sigma * sigma
    return g


def match_corner(coord, window_ext=5):
    r, c =  np.round(coord)
    window_orig = img_orig[r-window_ext:r+window_ext+1,
Esempio n. 38
0
def getMinorMajorRatio(image):
	image = image.copy()
	# Create the thresholded image to eliminate some of the background
	imagethr = np.where(image > np.mean(image),0.,1.0)
	imagethr2 = np.where(image > np.mean(image) - 2*np.std(image),0.,1.0)

	
	#Dilate the image
	imdilated = morphology.dilation(imagethr, np.ones((4,4)))

	# Create the label list
	label_list = measure.label(imdilated)
	label_list2 = imagethr2*label_list
	label_list = imagethr*label_list
	label_list2 = label_list2.astype(int)
	label_list = label_list.astype(int)
	   
	region_list = measure.regionprops(label_list, intensity_image=image)
	region_list2 = measure.regionprops(label_list2, intensity_image=image)
	maxregion,max2ndregion = getLargestRegions(region_list, label_list, imagethr)
	maxregion2,max2ndregion2 = getLargestRegions(region_list2, label_list2, imagethr2)

	# guard against cases where the segmentation fails by providing zeros
	ratio = 0.0
	fillratio = 0.0
	largeeigen = 0.0
	smalleigen = 0.0
	eigenratio = 0.0
	solidity = 0.0
	perimratio = 0.0
	arearatio = 0.0
	orientation = 0.0
	centroid = (0.0,0.0)
	cornercenter = 0.0
	cornerstd = 0.0
	lrdiff = 0.0
	tbdiff = 0.0
	hu1 = hu2 = hu3 = hu12 = hu13 = hu23 = 0.0
	whu1 = whu2 = whu3 = whu12 = whu13 = whu23 = 0.0
	extent = 0.0
	minintensity = maxintensity = meanintensity = 0.0
	intensityratio1 = intensityratio2 = intensityratio3 = 0.0
	if ((not maxregion is None) and  (maxregion.major_axis_length != 0.0)):
		corners = corner_peaks(corner_harris(maxregion.image), min_distance=5)
		corners_subpix = corner_subpix(maxregion.image, corners, window_size=13)
		cornercentercoords = np.nanmean(corners_subpix, axis=0)
		cornerstdcoords = np.nanstd(corners_subpix, axis=0)
		ratio = 0.0 if maxregion is None else  maxregion.minor_axis_length*1.0 / maxregion.major_axis_length
		largeeigen = 0.0 if maxregion is None else maxregion.inertia_tensor_eigvals[0]
		smalleigen = 0.0 if maxregion is None else maxregion.inertia_tensor_eigvals[1]
		fillratio = 0.0 if (maxregion2 is None or maxregion2.minor_axis_length == 0.0) else maxregion2.filled_area/(maxregion2.minor_axis_length*maxregion2.major_axis_length)
		solidity = 0.0 if maxregion2 is None else maxregion2.solidity
		hu1 = 0.0 if maxregion is None else maxregion.moments_hu[1]
		hu2 = 0.0 if maxregion is None else maxregion.moments_hu[2]
		hu3 = 0.0 if maxregion is None else maxregion.moments_hu[3]
		hu12 = 0.0 if (maxregion is None or hu1==0.0) else hu2/hu1
		hu13 = 0.0 if (maxregion is None or hu1==0.0) else hu3/hu1
		hu23 = 0.0 if (maxregion is None or hu2==0.0) else hu3/hu2
		whu1 = 0.0 if maxregion is None else maxregion.weighted_moments_hu[1]
		whu2 = 0.0 if maxregion is None else maxregion.weighted_moments_hu[2]
		whu3 = 0.0 if maxregion is None else maxregion.weighted_moments_hu[3]
		whu12 = 0.0 if (maxregion is None or whu1==0.0) else whu2/whu1
		whu13 = 0.0 if (maxregion is None or whu1==0.0) else whu3/whu1
		whu23 = 0.0 if (maxregion is None or whu2==0.0) else whu3/whu2
		extent = 0.0 if maxregion is None else maxregion.extent
		minintensity = 0.0 if maxregion is None else maxregion.min_intensity
		meanintensity = 0.0 if maxregion is None else maxregion.mean_intensity
		maxintensity = 0.0 if maxregion is None else maxregion.max_intensity
		intensityratio1 = 0.0 if (maxregion is None or maxintensity==0.0) else meanintensity/maxintensity
		intensityratio2 = 0.0 if (maxregion is None or maxintensity==0.0) else minintensity/maxintensity
		intensityratio3 = 0.0 if (maxregion is None or meanintensity==0.0) else minintensity/meanintensity
		perimratio = 0.0 if (maxregion is None or maxregion.minor_axis_length==0.0) else maxregion.perimeter/(maxregion.minor_axis_length*4.0+maxregion.major_axis_length*4.0)
		eigenratio = 0.0 if largeeigen == 0.0 else smalleigen/largeeigen
		orientation = 0.0 if maxregion is None else maxregion.orientation
		centroid = (0.0,0.0) if maxregion is None else maxregion.centroid
		cornercentercoords = np.absolute(cornercentercoords - centroid) if maxregion.major_axis_length==0.0 else np.absolute(cornercentercoords - centroid)/maxregion.major_axis_length
		cornercenter = np.linalg.norm(cornercentercoords)
		if maxregion.major_axis_length!=0.0: cornerstdcoords = np.absolute(cornerstdcoords)/maxregion.major_axis_length
		cornerstd = np.linalg.norm(cornerstdcoords)
		left = np.sum(maxregion.image[:,maxregion.image.shape[1]/2:])
		if maxregion.image.shape[1] % 2 == 0:
			right = np.sum(maxregion.image[:,:maxregion.image.shape[1]/2])
		else:
			right = np.sum(maxregion.image[:,:maxregion.image.shape[1]/2+1])
		lrdiff = np.abs((right-left)/(right+left)) 
		top = np.sum(maxregion.image[maxregion.image.shape[0]/2:,:])
		if maxregion.image.shape[0] % 2 == 0:
			bottom = np.sum(maxregion.image[:maxregion.image.shape[0]/2,:])
		else:
			bottom = np.sum(maxregion.image[:maxregion.image.shape[0]/2+1,:])
		tbdiff = np.abs((top-bottom)/(top+bottom)) 
	else:
		cornercentercoords = (0.0,0.0)
		cornerstdcoords = (0.0,0.0)
	if ((not maxregion is None) and (not max2ndregion is None)):
		arearatio = max2ndregion.area/maxregion.area
	#print perimratio
	if np.isnan(cornercenter):
		cornercenter = 0.0
	if sum(np.isnan(cornercentercoords)) > 0.0:
		cornercentercoords = np.array([0.0,0.0])
	if math.isnan(cornerstd):
		cornerstd = 0.0
	if sum(np.isnan(cornerstdcoords)) > 0.0:
		cornerstdcoords = np.array([0.0,0.0])
	return minintensity,meanintensity,maxintensity,intensityratio1,intensityratio2,intensityratio3,extent,lrdiff,tbdiff,cornercenter,cornercentercoords,cornerstd,cornerstdcoords,ratio,fillratio,eigenratio,solidity,hu1,hu2,hu3,hu12,hu13,hu23,whu1,whu2,whu3,whu12,whu13,whu23,perimratio,arearatio,orientation,centroid
Esempio n. 39
0
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from matplotlib import pyplot as plt

tmp = np.copy(arr_thresh[:, :, 0])
coords = corner_peaks(corner_harris(tmp), min_distance = 10)
coords_subpix = corner_subpix(tmp, coords, window_size = 13)

fig, ax = plt.subplots()
ax.imshow(tmp, interpolation='nearest', cmap=plt.cm.gray)
ax.plot(coords[:, 1], coords[:, 0], '.b', markersize=3)
ax.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15)
plt.show()

Esempio n. 40
0
def getMinorMajorRatio(image):
    features = {
        "axisratio": 0.0,
        "fillratio": 0.0,
        "eigenvals": np.array([0.0, 0.0]),
        "eigenratio": 0.0,
        "solidity": 0.0,
        "perimratio": 0.0,
        "arearatio": 0.0,
        "orientation": 0.0,
        "centroid": np.array([0.0, 0.0]),
        "wcentroiddiff": np.array([0.0, 0.0]),
        "cornerctr": 0.0,
        "cornerstd": 0.0,
        "cornerctrcoords": np.array([0.0, 0.0]),
        "cornerstdcoords": np.array([0.0, 0.0]),
        "lrdiff": 0.0,
        "tbdiff": 0.0,
        "hu": np.zeros(7, float),
        "huratios": np.zeros(3, float),
        "whu": np.zeros(7, float),
        "whuratios": np.zeros(3, float),
        "extent": 0.0,
        "minintensity": 0.0,
        "meanintensity": 0.0,
        "maxintensity": 0.0,
        "intensityratios": np.zeros(3, float),
        "vsobel": 0.0,
        "hsobel": 0.0,
        "felzen": 0.0,
        "peaklocalmax": 0.0,
        "hormean": 0.0,
        "horstd": 0.0,
        "vertmean": 0.0,
        "vertstd": 0.0,
        "horcount": 0.0,
        "vertcount": 0.0,
        "corners": 0.0,
        "area": 0.0,
        "bbox": np.zeros(4, float),
        "convex_area": 0.0,
        "eccentricity": 0.0,
        "equivalent_diameter": 0.0,
        "euler_number": 0.0,
        "filled_area": 0.0,
        "major_axis": 0.0,
        "minor_axis": 0.0,
        "moments": np.zeros(16, float),
        "moments_central": np.zeros(16, float),
        "moments_normalized": np.zeros(16, float),
        "perimeter": 0.0,
        "wcentroid": np.array([0.0, 0.0]),
        "weighted_moments": np.zeros(16, float),
        "weighted_moments_central": np.zeros(16, float),
        "weighted_moments_normalized": np.zeros(13, float),
        "original_size": 0,
    }
    image = image.copy()
    # Create the thresholded image to eliminate some of the background
    imagethr = np.where(image > np.mean(image), 0.0, 1.0)
    imagethr2 = np.where(image > np.mean(image) - 2 * np.std(image), 0.0, 1.0)

    # Dilate the image
    imdilated = morphology.dilation(imagethr, np.ones((4, 4)))

    # Create the label list
    label_list = measure.label(imdilated)
    label_list2 = imagethr2 * label_list
    label_list = imagethr * label_list
    label_list2 = label_list2.astype(int)
    label_list = label_list.astype(int)

    region_list = measure.regionprops(label_list, intensity_image=image)
    region_list2 = measure.regionprops(label_list2, intensity_image=image)
    maxregion, max2ndregion = getLargestRegions(region_list, label_list, imagethr)
    maxregion2, max2ndregion2 = getLargestRegions(region_list2, label_list2, imagethr2)

    # guard against cases where the segmentation fails by providing zeros
    if not maxregion is None:
        features["area"] = maxregion.area
        features["bbox"] = maxregion.bbox
        features["convex_area"] = maxregion.convex_area
        features["eccentricity"] = maxregion.eccentricity
        features["equivalent_diameter"] = maxregion.equivalent_diameter
        features["euler_number"] = maxregion.euler_number
        features["filled_area"] = maxregion.filled_area
        features["major_axis"] = maxregion.major_axis_length
        features["minor_axis"] = maxregion.minor_axis_length
        features["moments"] = maxregion.moments.flatten()
        features["moments_central"] = maxregion.moments_central.flatten()
        features["moments_normalized"] = maxregion.moments_normalized.flatten()[
            np.array([2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
        ]
        features["perimeter"] = maxregion.perimeter
        features["wcentroid"] = maxregion.weighted_centroid
        features["weighted_moments"] = maxregion.weighted_moments.flatten()
        features["weighted_moments_central"] = maxregion.weighted_moments_central.flatten()
        features["weighted_moments_normalized"] = maxregion.weighted_moments_normalized.flatten()[
            np.array([2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
        ]

        corners = corner_peaks(corner_harris(maxregion.image), min_distance=5)
        corners_subpix = corner_subpix(maxregion.image, corners, window_size=13)
        features["cornerctrcoords"] = np.nanmean(corners_subpix, axis=0)
        features["cornerstdcoords"] = np.nanstd(corners_subpix, axis=0)
        features["eigenvals"] = maxregion.inertia_tensor_eigvals
        features["hu"] = maxregion.moments_hu
        if not features["hu"][0] == 0.0:
            features["huratios"][0] = features["hu"][1] / features["hu"][0]
            features["huratios"][1] = features["hu"][2] / features["hu"][0]
        if not features["hu"][1] == 0.0:
            features["huratios"][2] = features["hu"][2] / features["hu"][1]
        features["whu"] = maxregion.weighted_moments_hu
        if not features["whu"][0] == 0.0:
            features["whuratios"][0] = features["whu"][1] / features["whu"][0]
            features["whuratios"][1] = features["whu"][2] / features["whu"][0]
        if not features["whu"][1] == 0.0:
            features["whuratios"][2] = features["whu"][2] / features["whu"][1]
        features["extent"] = maxregion.extent
        features["minintensity"] = maxregion.min_intensity
        features["meanintensity"] = maxregion.mean_intensity
        features["maxintensity"] = maxregion.max_intensity
        if not features["maxintensity"] == 0.0:
            features["intensityratios"][0] = features["meanintensity"] / features["maxintensity"]
            features["intensityratios"][1] = features["minintensity"] / features["maxintensity"]
        if not features["meanintensity"] == 0.0:
            features["intensityratios"][2] = features["minintensity"] / features["meanintensity"]
        if not maxregion.minor_axis_length == 0.0:
            features["perimratio"] = maxregion.perimeter / (
                maxregion.minor_axis_length * 4.0 + maxregion.major_axis_length * 4.0
            )
        if not features["eigenvals"][0] == 0.0:
            features["eigenratio"] = features["eigenvals"][1] / features["eigenvals"][0]
            # print features['eigenratio']
        features["orientation"] = maxregion.orientation
        features["centroid"] = maxregion.centroid
        features["wcentroiddiff"] = (
            np.absolute(features["centroid"] - np.asarray(maxregion.weighted_centroid)) / maxregion.major_axis_length
        )
        features["cornerctrcoords"] = (
            np.absolute(features["cornerctrcoords"] - features["centroid"])
            if maxregion.major_axis_length == 0.0
            else np.absolute(features["cornerctrcoords"] - features["centroid"]) / maxregion.major_axis_length
        )
        features["cornerctr"] = np.linalg.norm(features["cornerctrcoords"])
        if not maxregion.major_axis_length == 0.0:
            features["axisratio"] = maxregion.minor_axis_length / maxregion.major_axis_length
            features["cornerstdcoords"] = np.absolute(features["cornerstdcoords"]) / maxregion.major_axis_length
        features["cornerstd"] = np.linalg.norm(features["cornerstdcoords"])
        left = np.sum(maxregion.image[:, maxregion.image.shape[1] / 2 :])
        if maxregion.image.shape[1] % 2 == 0:
            right = np.sum(maxregion.image[:, : maxregion.image.shape[1] / 2])
        else:
            right = np.sum(maxregion.image[:, : maxregion.image.shape[1] / 2 + 1])
        features["lrdiff"] = np.abs((right - left) / (right + left))
        top = np.sum(maxregion.image[maxregion.image.shape[0] / 2 :, :])
        if maxregion.image.shape[0] % 2 == 0:
            bottom = np.sum(maxregion.image[: maxregion.image.shape[0] / 2, :])
        else:
            bottom = np.sum(maxregion.image[: maxregion.image.shape[0] / 2 + 1, :])
        features["tbdiff"] = np.abs((top - bottom) / (top + bottom))
        if not max2ndregion is None:
            features["arearatio"] = max2ndregion.area / maxregion.area
    if not maxregion2 is None:
        if not maxregion2.minor_axis_length == 0.0:
            features["fillratio"] = maxregion2.filled_area / (
                maxregion2.minor_axis_length * maxregion2.major_axis_length
            )
        features["solidity"] = maxregion2.solidity
    if np.isnan(features["cornerctr"]):
        features["cornerctr"] = 0.0
    if sum(np.isnan(features["cornerctrcoords"])) > 0.0:
        features["cornerctrcoords"] = np.array([0.0, 0.0])
    if math.isnan(features["cornerstd"]):
        features["cornerstd"] = 0.0
    if sum(np.isnan(features["cornerstdcoords"])) > 0.0:
        features["cornerstdcoords"] = np.array([0.0, 0.0])
    return features
# HARRIS CORNER DETECTION
# corner detection is based upon the change of the position vector with respect 
# to arc length. 
# approximates the autocorrelation function in the direction (u, v). A measure of
# curvature is given by the minimum value  obtained by considering the shifts (u, v)
# in the four main directions. That is, by (1,0), (0,−1), (0,1) and (−1,0). The minimum is chosen
# because it agrees with the following two observations. First, if the pixel is in an edge defining a
# straight line, is small for a shift along the edge and large for a shift perpendicular to
# the edge. In this case, we should choose the small value since the curvature of the edge is small.
# Secondly, if the edge defines a corner, then all the shifts produce a large value. Thus, if we also
# chose the minimum, this value indicates high curvature.

from skimage import data
import matplotlib.pyplot as plt
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.transform import warp, AffineTransform


tform = AffineTransform(scale=(1.3, 1.1), rotation=0, shear=0,translation=(0,0))#
image = warp(data.coins(), tform.inverse, output_shape=(500, 500))

coords = corner_peaks(corner_harris(image), min_distance=5)
coords_subpix = corner_subpix(image, coords, window_size=13)

plt.gray()
plt.imshow(image, interpolation='nearest')
plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15, mew=5)
plt.plot(coords[:, 1], coords[:, 0], '.b', markersize=7)
plt.axis('off')
plt.show()
Esempio n. 42
0
        image[230 + i:280 + i, 60 + i:110 + i] = 1

t = time.time()

if int(arg1) > 1:
    generate_squares()
else:
    generate_squares_niave()

print "took", time.time() - t

print "finding corners"
t = time.time()
coords = corner_peaks(corner_harris(image), min_distance=5)
print "took", time.time() - t

print "getting subpix"
t = time.time()

coords_subpix = corner_subpix(image, coords, 13, 0.99)

print "took", time.time() - t

print "plotting"
plt.gray()
plt.imshow(image, interpolation='nearest')
plt.plot(coords[:, 1], coords[:, 0], '.b', markersize=3)
plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15)
plt.axis((0, 500, 500, 0))
plt.show()
Esempio n. 43
0
def getMinorMajorRatio(image, features = features):
	features = features.copy()
	image = image.copy()
	# Create the thresholded image to eliminate some of the background
	imagethr = np.where(image > np.mean(image),0.,1.0)
	imagethr2 = np.where(image > np.mean(image) - 2*np.std(image),0.,1.0)

	#Dilate the image
	imdilated = morphology.dilation(imagethr, np.ones((4,4)))

	# Create the label list
	label_list = measure.label(imdilated)
	label_list2 = imagethr2*label_list
	label_list = imagethr*label_list
	label_list2 = label_list2.astype(int)
	label_list = label_list.astype(int)
	   
	region_list = measure.regionprops(label_list, intensity_image=image)
	region_list2 = measure.regionprops(label_list2, intensity_image=image)
	maxregion,max2ndregion = getLargestRegions(region_list, label_list, imagethr)
	maxregion2,max2ndregion2 = getLargestRegions(region_list2, label_list2, imagethr2)

	# guard against cases where the segmentation fails by providing zeros
	if not maxregion is None:
		features['area'] = maxregion.area
		features['bbox'] = maxregion.bbox
		features['convex_area'] = maxregion.convex_area
		features['eccentricity'] = maxregion.eccentricity
		features['equivalent_diameter'] = maxregion.equivalent_diameter
		features['euler_number'] = maxregion.euler_number
		features['filled_area'] = maxregion.filled_area
		features['major_axis'] = maxregion.major_axis_length
		features['minor_axis'] = maxregion.minor_axis_length
		features['moments'] = maxregion.moments.flatten()
		features['moments_central'] = maxregion.moments_central.flatten()
		features['moments_normalized'] = maxregion.moments_normalized.flatten()[np.array([2,3,5,6,7,8,9,10,11,12,13,14,15])]
		features['perimeter'] = maxregion.perimeter
		features['wcentroid'] = maxregion.weighted_centroid
		features['weighted_moments'] = maxregion.weighted_moments.flatten()
		features['weighted_moments_central'] = maxregion.weighted_moments_central.flatten()
		features['weighted_moments_normalized'] = maxregion.weighted_moments_normalized.flatten()[np.array([2,3,5,6,7,8,9,10,11,12,13,14,15])]

		corners = corner_peaks(corner_harris(maxregion.image), min_distance=5)
		corners_subpix = corner_subpix(maxregion.image, corners, window_size=13)
		features['cornerctrcoords'] = np.nanmean(corners_subpix, axis=0)
		features['cornerstdcoords'] = np.nanstd(corners_subpix, axis=0)
		features['eigenvals'] = maxregion.inertia_tensor_eigvals
		features['hu'] = maxregion.moments_hu
		if not features['hu'][0] == 0.0:
			features['huratios'][0] = features['hu'][1]/features['hu'][0]
			features['huratios'][1] = features['hu'][2]/features['hu'][0]
		if not features['hu'][1] == 0.0:
			features['huratios'][2] = features['hu'][2]/features['hu'][1]
		features['whu'] = maxregion.weighted_moments_hu
		if not features['whu'][0] == 0.0:
			features['whuratios'][0] = features['whu'][1]/features['whu'][0]
			features['whuratios'][1] = features['whu'][2]/features['whu'][0]
		if not features['whu'][1] == 0.0:
			features['whuratios'][2] = features['whu'][2]/features['whu'][1]
		features['extent'] = maxregion.extent
		features['minintensity'] = maxregion.min_intensity
		features['meanintensity'] = maxregion.mean_intensity
		features['maxintensity'] = maxregion.max_intensity
		if not features['maxintensity'] == 0.0:
			features['intensityratios'][0] = features['meanintensity']/features['maxintensity']
			features['intensityratios'][1] = features['minintensity']/features['maxintensity']
		if not features['meanintensity'] == 0.0:
			features['intensityratios'][2] = features['minintensity']/features['meanintensity']
		if not maxregion.minor_axis_length == 0.0:
			features['perimratio'] = maxregion.perimeter/(maxregion.minor_axis_length*4.0+maxregion.major_axis_length*4.0)
		if not features['eigenvals'][0] == 0.0:
			features['eigenratio'] = features['eigenvals'][1]/features['eigenvals'][0]
		features['orientation'] = maxregion.orientation
		features['centroid'] = maxregion.centroid
		features['wcentroiddiff'] = np.absolute(features['centroid']-np.asarray(maxregion.weighted_centroid))/maxregion.major_axis_length
		features['cornerctrcoords'] = np.absolute(features['cornerctrcoords'] - features['centroid']) if maxregion.major_axis_length==0.0 else np.absolute(features['cornerctrcoords'] - features['centroid'])/maxregion.major_axis_length
		features['cornerctr'] = np.linalg.norm(features['cornerctrcoords'])
		if not maxregion.major_axis_length == 0.0:
			features['axisratio'] = maxregion.minor_axis_length / maxregion.major_axis_length
			features['cornerstdcoords'] = np.absolute(features['cornerstdcoords'])/maxregion.major_axis_length
		features['cornerstd'] = np.linalg.norm(features['cornerstdcoords'])
		left = np.sum(maxregion.image[:,maxregion.image.shape[1]/2:])
		if maxregion.image.shape[1] % 2 == 0:
			right = np.sum(maxregion.image[:,:maxregion.image.shape[1]/2])
		else:
			right = np.sum(maxregion.image[:,:maxregion.image.shape[1]/2+1])
		features['lrdiff'] = np.abs((right-left)/(right+left)) 
		top = np.sum(maxregion.image[maxregion.image.shape[0]/2:,:])
		if maxregion.image.shape[0] % 2 == 0:
			bottom = np.sum(maxregion.image[:maxregion.image.shape[0]/2,:])
		else:
			bottom = np.sum(maxregion.image[:maxregion.image.shape[0]/2+1,:])
		features['tbdiff'] = np.abs((top-bottom)/(top+bottom)) 
		if not max2ndregion is None:
			features['arearatio'] = max2ndregion.area/maxregion.area
	if not maxregion2 is None:
		if not maxregion2.minor_axis_length == 0.0:
			features['fillratio'] = maxregion2.filled_area/(maxregion2.minor_axis_length*maxregion2.major_axis_length)
		features['solidity'] = maxregion2.solidity
	if np.isnan(features['cornerctr']):
		features['cornerctr'] = 0.0
	if sum(np.isnan(features['cornerctrcoords'])) > 0.0:
		features['cornerctrcoords'] = np.array([0.0,0.0])
	if math.isnan(features['cornerstd']):
		features['cornerstd'] = 0.0
	if sum(np.isnan(features['cornerstdcoords'])) > 0.0:
		features['cornerstdcoords'] = np.array([0.0,0.0])
	return features