Ejemplo n.º 1
0
def plot_ransac(segment_data_x, segment_data_y):
    data = np.column_stack([segment_data_x, segment_data_y])

    # fit line using all data
    model = LineModelND()
    model.estimate(data)

    # robustly fit line only using inlier data with RANSAC algorithm
    model_robust, inliers = ransac(data,
                                   LineModelND,
                                   min_samples=2,
                                   residual_threshold=1,
                                   max_trials=1000)
    outliers = inliers == False

    # generate coordinates of estimated models
    line_x = np.array([segment_data_x.min(), segment_data_x.max()])
    line_y = model.predict_y(line_x)
    line_y_robust = model_robust.predict_y(line_x)
    print("line_y_robust", line_y_robust)
    k = (line_y_robust[1] - line_y_robust[0]) / (line_x[1] - line_x[0])
    m = line_y_robust[0] - k * line_x[0]
    x0 = (segment_data_y.min() - m) / k
    x1 = (segment_data_y.max() - m) / k
    line_x_y = np.array([x0, x1])
    line_y_robust_y = model_robust.predict_y(line_x_y)
    if (distance(line_x[0], line_y_robust[0], line_x[1], line_y_robust[1]) <
            distance(line_x_y[0], line_y_robust_y[0], line_x_y[1],
                     line_y_robust_y[1])):
        plt.plot(line_x, line_y_robust, '-b', label='Robust line model')
    else:
        plt.plot(line_x_y, line_y_robust_y, '-b', label='Robust line model')
Ejemplo n.º 2
0
def test_deprecated_params_attribute():
    model = LineModelND()
    model.params = ((0, 0), (1, 1))
    x = np.arange(-10, 10)
    y = model.predict_y(x)
    with expected_warnings(['`_params`']):
        assert_equal(model.params, model._params)
Ejemplo n.º 3
0
def test_line_modelND_estimate():
    # generate original data without noise
    model0 = LineModelND()
    model0.params = (np.array([0,0,0], dtype='float'),
                         np.array([1,1,1], dtype='float')/np.sqrt(3))
    # we scale the unit vector with a factor 10 when generating points on the
    # line in order to compensate for the scale of the random noise
    data0 = (model0.params[0] +
             10 * np.arange(-100,100)[...,np.newaxis] * model0.params[1])

    # add gaussian noise to data
    random_state = np.random.RandomState(1234)
    data = data0 + random_state.normal(size=data0.shape)

    # estimate parameters of noisy data
    model_est = LineModelND()
    model_est.estimate(data)

    # test whether estimated parameters are correct
    # we use the following geometric property: two aligned vectors have
    # a cross-product equal to zero
    # test if direction vectors are aligned
    assert_almost_equal(np.linalg.norm(np.cross(model0.params[1],
                                                model_est.params[1])), 0, 1)
    # test if origins are aligned with the direction
    a = model_est.params[0] - model0.params[0]
    if np.linalg.norm(a) > 0:
        a /= np.linalg.norm(a)
    assert_almost_equal(np.linalg.norm(np.cross(model0.params[1], a)), 0, 1)
Ejemplo n.º 4
0
def test_line_model_nd_residuals():
    model = LineModelND()
    model.params = (np.array([0, 0, 0]), np.array([0, 0, 1]))
    assert_equal(abs(model.residuals(np.array([[0, 0, 0]]))), 0)
    assert_equal(abs(model.residuals(np.array([[0, 0, 1]]))), 0)
    assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)
    # test params argument in model.rediduals
    data = np.array([[10, 0, 0]])
    params = (np.array([0, 0, 0]), np.array([2, 0, 0]))
    assert_equal(abs(model.residuals(data, params=params)), 30)
    def compute_ransac_angles(self,
                              x_data,
                              y_data,
                              n_win=10,
                              n_trials=100,
                              verbose=False):

        # storage of angles
        angs = []
        ss = []
        startTime = time()

        # loop through data
        # TODO: Performance edge cases. It would be unfortunate to start our data stream at a corner
        for idx in range(len(y_data) - n_win):

            # cut window / loop throuh based on n_win
            x_curs = x_data[idx:idx + n_win]
            y_curs = y_data[idx:idx + n_win]

            # setup RANSAC
            model_LMND = LineModelND()
            points = np.column_stack([x_curs, y_curs])
            model_LMND.estimate(points)

            # RANSAC
            model_RANSAC, _ = ransac(points,
                                     LineModelND,
                                     min_samples=2,
                                     residual_threshold=5,
                                     max_trials=n_trials)

            # compute lines
            x_range = np.array([x_curs.min(), x_curs.max()])
            y_range = model_LMND.predict_y(x_range)
            y_range_RANSAC = model_RANSAC.predict_y(x_range)
            slope = (y_range_RANSAC[1] - y_range_RANSAC[0]) / \
                (x_range[1] - x_range[0])

            #print("y_range_RANSAC:", y_range_RANSAC)

            # store angle

            angs.append(np.arctan(slope))
            ss.append(slope)

        angs = np.array(angs)
        ss = np.array(ss)
        angs[angs > 1.5] = angs[angs > 1.5] - np.pi  # ??

        print('Total time: %fs' % (time() - startTime))
        print("angs: ", ss)
        return angs, ss
Ejemplo n.º 6
0
    def line_fitting(self, data):
        # Please do not modify the header

        # fit a line the to arena wall using RANSAC
        # return two lists containing slopes and y intercepts of the line

        ########################
        ######## YOUR CODE HERE
        ########################
        model = LineModelND()
        model.estimate(data)
        slope = []
        intercept = []
        for image in data:
            rgb_weights = [0.2989, 0.5870, 0.1140]
            gray_image = np.dot(image[..., :3], rgb_weights)
            edges = feature.canny(gray_image,
                                  sigma=2,
                                  low_threshold=0.9,
                                  high_threshold=0.999,
                                  mask=None,
                                  use_quantiles=True)
            # v = viewer.ImageViewer(edges)
            # v.show()
            ransac_model, inliers = ransac(np.argwhere(edges),
                                           model_class=measure.LineModelND,
                                           min_samples=2,
                                           residual_threshold=1,
                                           max_trials=15,
                                           stop_sample_num=float('inf'),
                                           stop_residuals_sum=0,
                                           stop_probability=1,
                                           random_state=1,
                                           initial_inliers=None)
            outliers = inliers == False
            (origin, direction) = np.round(ransac_model.params, 5)
            slope_temp = direction[0] / direction[
                1]  #(finding change in y over change in x)
            intercept_temp = origin[0] - slope_temp * origin[
                1]  #(finding y intercept)
            # plt.imshow(gray_image, cmap=plt.cm.gray)
            # line_y = np.arange(0, 250)
            # line_x = ransac_model.predict_x(line_y)
            # p1 = origin
            # p2 = direction
            # plt.plot(line_y, line_x, color='#ff0000', linewidth=1.5)
            # plt.show()
            slope.append(slope_temp)
            intercept.append(intercept_temp)
        # Please do not modify the return type below

        return slope, intercept
Ejemplo n.º 7
0
def test_2D():
    np.random.seed(seed=1)

    # generate coordinates of line
    x = np.arange(-200, 200)
    y = 0.2 * x + 20
    data = np.column_stack([x, y])

    # add gaussian noise to coordinates
    noise = np.random.normal(size=data.shape)
    data += 0.5 * noise
    data[::2] += 5 * noise[::2]
    data[::4] += 20 * noise[::4]

    # add faulty data
    faulty = np.array(30 * [(180., -100)])
    faulty += 10 * np.random.normal(size=faulty.shape)
    data[:faulty.shape[0]] = faulty

    # fit line using all data
    model = LineModelND()
    model.estimate(data)

    # robustly fit line only using inlier data with RANSAC algorithm
    model_robust, inliers = ransac(data,
                                   LineModelND,
                                   min_samples=2,
                                   residual_threshold=1,
                                   max_trials=1000)
    outliers = inliers == False

    # generate coordinates of estimated models
    line_x = np.arange(-250, 250)
    line_y = model.predict_y(line_x)
    line_y_robust = model_robust.predict_y(line_x)

    fig, ax = plt.subplots()
    ax.plot(data[inliers, 0],
            data[inliers, 1],
            '.b',
            alpha=0.6,
            label='Inlier data')
    ax.plot(data[outliers, 0],
            data[outliers, 1],
            '.r',
            alpha=0.6,
            label='Outlier data')
    ax.plot(line_x, line_y, '-k', label='Line model from all data')
    ax.plot(line_x, line_y_robust, '-b', label='Robust line model')
    ax.legend(loc='lower left')
    plt.show()
Ejemplo n.º 8
0
def test_line_model_nd_invalid_input():
    with testing.raises(ValueError):
        LineModelND().predict_x(np.zeros(1))

    with testing.raises(ValueError):
        LineModelND().predict_y(np.zeros(1))

    with testing.raises(ValueError):
        LineModelND().predict_x(np.zeros(1), np.zeros(1))

    with testing.raises(ValueError):
        LineModelND().predict_y(np.zeros(1))

    with testing.raises(ValueError):
        LineModelND().predict_y(np.zeros(1), np.zeros(1))

    with testing.raises(ValueError):
        LineModelND().estimate(np.empty((1, 3)))

    with testing.raises(ValueError):
        LineModelND().residuals(np.empty((1, 3)))

    data = np.empty((1, 2))
    with testing.raises(ValueError):
        LineModelND().estimate(data)
def test_line_model_estimate():
    # generate original data without noise
    model0 = LineModelND()
    model0.params = ((0, 0), (1, 1))
    x0 = np.arange(-100, 100)
    y0 = model0.predict_y(x0)

    data = np.column_stack([x0, y0])

    # estimate parameters of noisy data
    model_est = LineModelND()
    model_est.estimate(data)

    # test whether estimated parameters almost equal original parameters
    x = np.random.rand(100, 2)
    assert_almost_equal(model0.predict(x), model_est.predict(x), 1)
def test_line_model_residuals():
    model = LineModelND()
    model.params = (np.array([0, 0]), np.array([0, 1]))
    assert_equal(model.residuals(np.array([[0, 0]])), 0)
    assert_equal(model.residuals(np.array([[0, 10]])), 0)
    assert_equal(model.residuals(np.array([[10, 0]])), 10)
    model.params = (np.array([-2, 0]), np.array([1, 1]) / np.sqrt(2))
    assert_equal(model.residuals(np.array([[0, 0]])), np.sqrt(2))
    assert_almost_equal(model.residuals(np.array([[-4, 0]])), np.sqrt(2))
Ejemplo n.º 11
0
    def fitCluster(self, hits, plotting=False):
        #print (hits)
        x = np.array([h[0] for h in hits])
        y = np.array([h[1] for h in hits])
        data = np.column_stack([x, y])

        # fit line using all data
        model = LineModelND()
        model.estimate(data)

        # robustly fit line only using inlier data with RANSAC algorithm
        model_robust, inliers = ransac(
            data,
            LineModelND,
            min_samples=self.min_samples_ransac,
            residual_threshold=self.residual_threshold_ransac,
            max_trials=self.max_trials_ransac)
        outliers = inliers == False

        line_x = np.arange(0, self.npixx)
        line_y = model.predict_y(line_x)
        line_y_robust = model_robust.predict_y(line_x)

        if plotting:
            import matplotlib.pyplot as plt
            fig, ax = plt.subplots()
            ax.plot(data[inliers, 0],
                    data[inliers, 1],
                    '.b',
                    alpha=0.6,
                    label='Inlier data')
            ax.plot(data[outliers, 0],
                    data[outliers, 1],
                    '.r',
                    alpha=0.6,
                    label='Outlier data')
            ax.plot(line_x, line_y, '-k', label='Line model from all data')
            ax.plot(line_x, line_y_robust, '-b', label='Robust line model')
            ax.set_ylim(0, self.npixx)
            ax.legend(loc='lower left')
            plt.show()

        extrap_xy = np.column_stack([line_x, line_y]).astype(int)
        extrap_xy_robust = np.column_stack([line_x, line_y_robust]).astype(int)
        return extrap_xy, extrap_xy_robust
Ejemplo n.º 12
0
def test_line_model_nd_estimate():
    # generate original data without noise
    model0 = LineModelND()
    model0.params = (np.array([0, 0, 0], dtype='float'),
                     np.array([1, 1, 1], dtype='float') / np.sqrt(3))
    # we scale the unit vector with a factor 10 when generating points on the
    # line in order to compensate for the scale of the random noise
    data0 = (model0.params[0] +
             10 * np.arange(-100, 100)[..., np.newaxis] * model0.params[1])

    # add gaussian noise to data
    random_state = np.random.RandomState(1234)
    data = data0 + random_state.normal(size=data0.shape)

    # estimate parameters of noisy data
    model_est = LineModelND()
    model_est.estimate(data)
    # assert_almost_equal(model_est.residuals(data0), np.zeros(len(data)), 1)

    # test whether estimated parameters are correct
    # we use the following geometric property: two aligned vectors have
    # a cross-product equal to zero
    # test if direction vectors are aligned
    assert_almost_equal(
        np.linalg.norm(np.cross(model0.params[1], model_est.params[1])), 0, 1)
    # test if origins are aligned with the direction
    a = model_est.params[0] - model0.params[0]
    if np.linalg.norm(a) > 0:
        a /= np.linalg.norm(a)
    assert_almost_equal(np.linalg.norm(np.cross(model0.params[1], a)), 0, 1)
Ejemplo n.º 13
0
def test_line_model_residuals():
    model = LineModelND()
    model.params = (np.array([0, 0]), np.array([0, 1]))
    assert_equal(model.residuals(np.array([[0, 0]])), 0)
    assert_equal(model.residuals(np.array([[0, 10]])), 0)
    assert_equal(model.residuals(np.array([[10, 0]])), 10)
    model.params = (np.array([-2, 0]), np.array([1, 1])  / np.sqrt(2))
    assert_equal(model.residuals(np.array([[0, 0]])), np.sqrt(2))
    assert_almost_equal(model.residuals(np.array([[-4, 0]])), np.sqrt(2))
Ejemplo n.º 14
0
def test_line_model_nd_invalid_input():
    assert_raises(AssertionError, LineModelND().predict_x, np.zeros(1))
    assert_raises(ValueError, LineModelND().predict_x, np.zeros(1), np.zeros(1))
    assert_raises(AssertionError, LineModelND().predict_y, np.zeros(1))
    assert_raises(ValueError, LineModelND().predict_y, np.zeros(1), np.zeros(1))
    assert_raises(ValueError, LineModelND().estimate, np.empty((1, 3)))
    assert_raises(AssertionError, LineModelND().residuals, np.empty((1, 3)))
Ejemplo n.º 15
0
    def generate_plottable_points_along_line(model:LineModelND, xmin:int,xmax:int, ymin:int, ymax:int):
        """
        Computes points along the specified line model
        The visual range is 
        between xmin and xmax along X axis
            and
        between ymin and ymax along Y axis
        return shape is [[x1,y1],[x2,y2]]
        """
        unit_vector=model.params[1]
        slope=abs(unit_vector[1]/unit_vector[0])
        x_values=None
        y_values=None
        if (slope > 1):
            y_values=np.arange(ymin, ymax,1)
            x_values=model.predict_x(y_values)
        else:        
            x_values=np.arange(xmin, xmax,1)
            y_values=model.predict_y(x_values)

        np_data_points=np.column_stack((x_values,y_values)) 
        return np_data_points
Ejemplo n.º 16
0
def test_line_model_estimate():
    # generate original data without noise
    model0 = LineModelND()
    model0.params = ((0, 0), (1, 1))
    x0 = np.arange(-100, 100)
    y0 = model0.predict_y(x0)

    data = np.column_stack([x0, y0])

    # estimate parameters of noisy data
    model_est = LineModelND()
    model_est.estimate(data)

    # test whether estimated parameters almost equal original parameters
    x = np.random.rand(100, 2)
    assert_almost_equal(model0.predict(x), model_est.predict(x), 1)
Ejemplo n.º 17
0
def show_ransac_points_line(points,  min_samples=2, residual_threshold=0.1, max_trials=1000, Xrange = 100, displayoutlier= False):
   
    # fit line using all data
 model = LineModelND()
 if(len(points) > 2):
  model.estimate(points)
 
  fig, ax = plt.subplots()   

  # robustly fit line only using inlier data with RANSAC algorithm
  model_robust, inliers = ransac(points, LineModelND, min_samples=min_samples,
                               residual_threshold=residual_threshold, max_trials=max_trials)
  slope , intercept = model_robust.params
 
  outliers = inliers == False
  # generate coordinates of estimated models
  line_x = np.arange(0, Xrange)
  line_y = model.predict_y(line_x)
  line_y_robust = model_robust.predict_y(line_x)
 
  #print('Model Fit' , 'yVal = ' , line_y_robust)
  #print('Model Fit', 'xVal = ' , line_x)
  ax.plot(points[inliers, 0], points[inliers, 1], '.b', alpha=0.6,
        label='Inlier data')
  if displayoutlier:
   ax.plot(points[outliers, 0], points[outliers, 1], '.r', alpha=0.6,
        label='Outlier data')
  #ax.plot(line_x, line_y, '-r', label='Normal line model')
  ax.plot(line_x, line_y_robust, '-g', label='Robust line model')
  ax.legend(loc='upper left')
   
  ax.set_xlabel('Time (s)')
  ax.set_ylabel('Thickness (um)')
  print('Ransac Slope = ', str('%.3e'%((line_y_robust[Xrange - 1] - line_y_robust[0])/ (Xrange)) )) 
  print('Regression Slope = ', str('%.3e'%((line_y[Xrange - 1] - line_y_robust[0])/ (Xrange)) )) 
  print('Mean Thickness (After outlier removal) = ', str('%.3f'%(sum(points[inliers, 1])/len(points[inliers, 1]))), 'um')   
  plt.show()
Ejemplo n.º 18
0
def ransa(array3):
    array5 = []
    array4 = []
    l = []
    data = np.zeros((len(array3), 2))
    for g in range(len(array3)):
        data[g] = (array3[g][0][0], array3[g][0][1])
        l.append(array3[g][0][0])

    # fit line using all data
    model = LineModelND()
    model.estimate(data)

    # robustly fit line only using inlier data with RANSAC algorithm
    model_robust, inliers = ransac(data, LineModelND, min_samples=2,
                                   residual_threshold=1, max_trials=1000)
    outliers = inliers == False

    # generate coordinates of estimated models
    line_x = l
    line_y = model.predict_y(line_x)
    line_y_robust = model_robust.predict_y(line_x)

    for t in range(len(array3)):
        for f in range(len(line_x)):
            if abs(array3[t][0][0] - line_x[f]) <= 20 and abs(array3[t][0][1] - line_y_robust[f]) <= 20:
                if array3[t] not in array4:
                    array4.append(array3[t])

    if len(array4) >= 9:
        for po in range(len(array4)):
            if abs(array4[po][0][0] - pixel1) < 200 and abs(array4[po][0][1] - pixel2) < 200:
                array5.append(array4[po])
    else:
        array5 = array4.copy()
    return array5
Ejemplo n.º 19
0
def find_darts_axis(processed_image):
    """
    Applies a total least squares estimator to the image that is processed this iteration. The function evaluates the
    image data and takes the bounding box into consideration.
    For the estimation, the x-axis is vertical to processed_image.image (from top to bottom). The y-axis is horizontal
    (from left to right). The represented line follows through the shaft of the dart.

    :param processed_image: image that is processed.
    :type processed_image: ProcessedImage
    :return: An array of y-coordinates. array is as long as the bounding box is high.
    :rtype: [int]
    """
    if processed_image.has_bounding_box():
        x = processed_image.bounding_box.x
        y = processed_image.bounding_box.y
        w = processed_image.bounding_box.w
        h = processed_image.bounding_box.h
        segmented_image = processed_image.image[y:y + h, x:x + w]

        # find points that are white
        data = np.argwhere(segmented_image == 255)
        if len(data) < 2:
            return None

        # estimate least squares
        model = LineModelND()
        model.estimate(data)

        top_y = np.arange(0 - y, h)

        try:
            return model.predict_y(top_y)
        except ValueError:  # Can occur when axis is parallel to dartboard
            return None

    return None
Ejemplo n.º 20
0
def test_line_model_nd_residuals():
    model = LineModelND()
    model.params = (np.array([0, 0, 0]), np.array([0, 0, 1]))
    assert_equal(abs(model.residuals(np.array([[0, 0, 0]]))), 0)
    assert_equal(abs(model.residuals(np.array([[0, 0, 1]]))), 0)
    assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)
    # test params argument in model.rediduals
    data = np.array([[10, 0, 0]])
    params = (np.array([0, 0, 0]), np.array([2, 0, 0]))
    assert_equal(abs(model.residuals(data, params=params)), 30)
Ejemplo n.º 21
0
def test_line_modelND_under_determined():
    data = np.empty((1, 3))
    with testing.raises(ValueError):
        LineModelND().estimate(data)
Ejemplo n.º 22
0
#print(x,y)
x, y = map(list, zip(*cartesian))
#print(cartesian)
#plt.scatter(y,x)
#plt.show()

# generate coordinates of line
#x = np.arange(-200, 200)

#y = 0.2 * x + 20
data = np.column_stack([x, y])

print(data)

# fit line using all data
model = LineModelND()
model.estimate(data)  # estimate random data

# robustly fit line only using inlier data with RANSAC algorithm
model_robust, inliers = ransac(data,
                               LineModelND,
                               min_samples=2,
                               residual_threshold=1,
                               max_trials=1000)
outliers = inliers == False

# generate coordinates of estimated models
line_x = np.arange(data.min(), data.max())
line_y = model.predict_y(line_x)
line_y_robust = model_robust.predict_y(line_x)
print(line_y_robust)
Ejemplo n.º 23
0
def test_line_modelND_residuals():
    model = LineModelND()
    model.params = (np.array([0, 0, 0]), np.array([0, 0, 1]))
    assert_equal(abs(model.residuals(np.array([[0, 0, 0]]))), 0)
    assert_equal(abs(model.residuals(np.array([[0, 0, 1]]))), 0)
    assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)
Ejemplo n.º 24
0
y = 0.2 * x + 20
data = np.column_stack([x, y])

# add faulty data
faulty = np.array(30 * [(180., -100)])
faulty += 5 * np.random.normal(size=faulty.shape)
data[:faulty.shape[0]] = faulty

# add gaussian noise to coordinates
noise = np.random.normal(size=data.shape)
data += 0.5 * noise
data[::2] += 5 * noise[::2]
data[::4] += 20 * noise[::4]

# fit line using all data
model = LineModelND()
model.estimate(data)

# robustly fit line only using inlier data with RANSAC algorithm
model_robust, inliers = ransac(data, LineModelND, min_samples=2,
                               residual_threshold=1, max_trials=1000)
outliers = inliers == False

# generate coordinates of estimated models
line_x = np.arange(-250, 250)
line_y = model.predict_y(line_x)
line_y_robust = model_robust.predict_y(line_x)

fig, ax = plt.subplots()
ax.plot(data[inliers, 0], data[inliers, 1], '.b', alpha=0.6,
        label='Inlier data')
Ejemplo n.º 25
0
def test_line_modelND_predict():
    model = LineModelND()
    model.params = (np.array([0, 0]), np.array([0.2, 0.98]))
    x = np.arange(-10, 10)
    y = model.predict_y(x)
    assert_almost_equal(x, model.predict_x(y))
# storage of angles
angs = []

startTime = time()

# loop through data
# TODO: Performance edge cases.
for idx in range(len(y_data) - n_win):

    # cut window
    x_curs = x_data[idx:idx + n_win]
    y_curs = y_data[idx:idx + n_win]

    # setup RANSAC
    model_LMND = LineModelND()
    points = np.column_stack([x_curs, y_curs])
    model_LMND.estimate(points)

    # RANSAC
    model_RANSAC, _ = ransac(points,
                             LineModelND,
                             min_samples=2,
                             residual_threshold=5,
                             max_trials=1000)

    # compute lines
    x_range = np.array([x_curs.min(), x_curs.max()])
    y_range = model_LMND.predict_y(x_range)
    y_range_RANSAC = model_RANSAC.predict_y(x_range)
    slope = (y_range_RANSAC[1] - y_range_RANSAC[0]) / (x_range[1] - x_range[0])
Ejemplo n.º 27
0
def test_line_model_predict():
    model = LineModelND()
    model.params = ((0, 0), (1, 1))
    x = np.arange(-10, 10)
    y = model.predict_y(x)
    assert_almost_equal(x, model.predict_x(y))
Ejemplo n.º 28
0
x = x.reshape(-1, 1)
y = y.reshape(-1, 1)

data = np.column_stack([x, y])
data1 = data

############# RANSAC Start ##################
inliersArray = np.array([])
print("inliersArray", inliersArray)
dataSize = data.size
print("data size", dataSize)

while dataSize >= 20:
    #print('dataSize: ', dataSize)
    model = LineModelND()
    model.estimate(data)
    # robustly fit line only using inlier data with RANSAC algorithm
    model_robust, inliers = ransac(data,
                                   LineModelND,
                                   min_samples=2,
                                   residual_threshold=60,
                                   max_trials=100)
    outliers = inliers == False
    # generate coordinates of estimated models
    line_x = np.arange(x.min(), x.max())  #[:, np.newaxis]
    line_y = model.predict_y(line_x)
    line_y_robust = model_robust.predict_y(line_y)
    detectedByRansac = np.column_stack([data[inliers, 0], data[inliers, 1]])
    #print('detectedByRansac: ', detectedByRansac)
Ejemplo n.º 29
0
xx = np.arange(-250, 250)
plt.plot(xx, m * xx + c, 'r-');   


# <markdowncell>
# Scikit-image provides an N-dimensional LineModel object that encapsulates the
# above:



# <codecell>

from skimage.measure import ransac, LineModelND

model = LineModelND()
model.estimate(data)
model.params   


# <markdowncell>
# Instead of ``m`` and ``c``, it parameterizes the line by ``origin``
# and ``direction`` --- much safer when dealing with vertical lines,
# e.g.!



# <codecell>

origin, direction = model.params
plt.plot(x, y, 'b.')
    def compile_walls(self,
                      trans_slide,
                      x_data,
                      y_data,
                      n_trials=100,
                      verbose=False):
        # the idea of this function is to compute RANSAC lines on stable regions (walls) as opposed to unstable corners

        offset = 1

        # pad array to full data length
        trans_fill = fill_arr(trans_slide, False, len(x_data), offset=offset)

        # pairwise XOR (exclusive or), looking for changes in transition regions
        t_idx = [
            trans_fill[i] != trans_fill[i + 1]
            for i in range(len(trans_fill) - 1)
        ]

        # reassemble these segment points
        seg_pts = np.concatenate(([0], np.where(t_idx)[0], [len(x_data) - 1]))

        it = iter(seg_pts)
        wall_lines = []

        # loop through wall segments (two points at a time as a line needs two points)
        for p1 in it:
            p2 = next(it)

            # cut window
            x_curs = x_data[p1:p2]
            y_curs = y_data[p1:p2]

            # ignore small segments
            if len(x_curs) < 5:
                continue

            # setup RANSAC
            model_LMND = LineModelND()
            points = np.column_stack([x_curs, y_curs])
            model_LMND.estimate(points)

            # RANSAC
            model_RANSAC, _ = ransac(points,
                                     LineModelND,
                                     min_samples=2,
                                     residual_threshold=5,
                                     max_trials=n_trials)

            # compute lines
            x_range = np.array([x_curs.min(), x_curs.max()])
            y_range = model_LMND.predict_y(x_range)
            y_range_RANSAC = model_RANSAC.predict_y(x_range)
            slope = (y_range_RANSAC[1] - y_range_RANSAC[0]) / (x_range[1] -
                                                               x_range[0])

            y_range_robust = model_RANSAC.predict_y(x_range)
            k = (y_range_robust[1] - y_range_robust[0]) / \
                (x_range[1] - x_range[0])

            m = y_range_robust[0] - k * x_range[0]
            x0 = (y_curs.min() - m) / k
            x1 = (y_curs.max() - m) / k
            x_range_y = np.array([x0, x1])
            y_range_robust_y = model_RANSAC.predict_y(x_range_y)
            ww = (y_range_robust_y[1] - y_range_robust_y[0]) / (x_range_y[1] -
                                                                x_range_y[0])

            if (distance(x_range[0], y_range_robust[0],
                         x_range[1], y_range_robust[1]) < distance(
                             x_range_y[0], y_range_robust_y[0], x_range_y[1],
                             y_range_robust_y[1])):
                x_range_r = x_range
                y_range_r = y_range_robust
            else:
                plt.plot(x_range_y,
                         y_range_robust_y,
                         '-r',
                         label='Robust line model')
                x_range_r = x_range_y
                y_range_r = y_range_robust_y

            # what is the absolute distance the wall spans?
            x_span = np.abs(x_range_r[1] - x_range_r[0])
            y_span = np.abs(y_range_r[1] - y_range_r[0])

            if verbose:
                plt.scatter(x_data, y_data)
                plt.scatter(x_curs, y_curs)
                plt.plot(x_range_r, y_range_r, '-r', label='Robust line model')
                plt.axis('equal')
                plt.show()
                print('x_span: %f, y_span: %f' % (x_span, y_span))

            # do not record if span is too small (tiny walls can be unstable)
            if x_span < 200 and y_span < 200:
                continue

            # record wall line points (these are arbitrary and are not end points!)
            p1 = np.array((x_range_r[0], y_range_r[0]))
            p2 = np.array((x_range_r[1], y_range_r[1]))
            wall_lines.append((p1, p2))

        wall_lines = np.array(wall_lines)
        return wall_lines
Ejemplo n.º 31
0
def test_line_model_nd_under_determined():
    assert_raises(ValueError, LineModelND().estimate, np.empty((1, 3)))
Ejemplo n.º 32
0
def test_line_model_invalid_input():
    with testing.raises(ValueError):
        LineModelND().estimate(np.empty((1, 3)))
Ejemplo n.º 33
0
def test_line_model_predict():
    model = LineModelND()
    model.params = ((0, 0), (1, 1))
    x = np.arange(-10, 10)
    y = model.predict_y(x)
    assert_almost_equal(x, model.predict_x(y))
def test_line_model_under_determined():
    data = np.empty((1, 2))
    assert_raises(ValueError, LineModelND().estimate, data)
Ejemplo n.º 35
0
def test_line_model_nd_predict():
    model = LineModelND()
    model.params = (np.array([0, 0]), np.array([0.2, 0.8]))
    x = np.arange(-10, 10)
    y = model.predict_y(x)
    assert_almost_equal(x, model.predict_x(y))
def test_line_model_invalid_input():
    assert_raises(ValueError, LineModelND().estimate, np.empty((1, 3)))
def test_line_modelND_residuals():
    model = LineModelND()
    model.params = (np.array([0, 0, 0]), np.array([0, 0, 1]))
    assert_equal(abs(model.residuals(np.array([[0, 0, 0]]))), 0)
    assert_equal(abs(model.residuals(np.array([[0, 0, 1]]))), 0)
    assert_equal(abs(model.residuals(np.array([[10, 0, 0]]))), 10)
Ejemplo n.º 38
0
def iter_ransac(image, sigma=3, no_iter=10, order='col', mxt=2500):

    # The plan here is to make the outliers inliers each time or summit

    outArray = np.zeros_like(image)

    #th = filters.threshold_otsu(inArray)

    bw = canny(image, sigma=sigma)

    inDex = np.where(bw > 0)

    if order == 'col':

        inData = np.column_stack([inDex[0], inDex[1]])

    if order == 'row':
        inData = np.column_stack([inDex[1], inDex[0]])

    for i in tqdm(range(0, no_iter)):

        #        if orient == 'v':

        if order == 'col':

            #inData = np.column_stack([inDex[0], inDex[1]])

            model = LineModelND()
            model.estimate(inData)

            model_robust, inliers = ransac(inData,
                                           LineModelND,
                                           min_samples=2,
                                           residual_threshold=1,
                                           max_trials=mxt)

            outliers = np.invert(inliers)

            line_x = inData[:, 0]
            line_y = model.predict_y(line_x)
            line_y_robust = model_robust.predict_y(line_x)

            outArray[line_x, np.int64(np.round(line_y_robust))] = 1

        if order == 'row':

            #            inData = np.column_stack([inDex[1], inDex[0]])

            model = LineModelND()
            model.estimate(inData)

            model_robust, inliers = ransac(inData,
                                           LineModelND,
                                           min_samples=2,
                                           residual_threshold=1,
                                           max_trials=mxt)

            outliers = np.invert(inliers)

            line_x = inData[:, 0]
            line_y = model.predict_y(line_x)

            line_y_robust = model_robust.predict_y(line_x)

            outArray[np.int64(np.round(line_y_robust)), line_x] = 1


#

        inData = inData[:, 0:2][outliers == True]
        del model, model_robust, inliers, outliers

    return outArray