Commit 7e2c2567 authored by kberry's avatar kberry
Browse files

First draft of slope-filtering

parent c98858a5
Loading
Loading
Loading
Loading
+33 −0
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@ import tempfile
import os
import fnmatch
import numpy as np
import pandas as pd

def create_dir(basedir=''):
    """
@@ -34,3 +35,35 @@ def file_search(searchdir,searchstring):
            filelist.append(os.path.join(root, filename))
    filelist=np.array(filelist)
    return filelist    

# TODO: FIXME
def calculate_slope(x1, x2, y1, y2):
    """

    Parameters
    ----------
    x1
    x2
    y1
    y2

    Returns
    -------

    """
    return (x2-x1)/(y2-y1)

def calculate_slope(x1, x2):
    """

    Parameters
    ----------
    x1
    x2

    Returns
    -------

    """
    slopes = (x2.y.values - x1.y.values)/(x2.x.values-x1.x.values)
    return pd.DataFrame(slopes, columns=['slope'])
+11 −1
Original line number Diff line number Diff line
@@ -8,7 +8,7 @@ import numpy as np
import numpy.testing
import pandas as pd
from autocnet.transformation import transformations

from autocnet.fileio import utils

class TestHomography(unittest.TestCase):

@@ -64,6 +64,16 @@ class TestFundamentalMatrix(unittest.TestCase):

        self.assertIsInstance(F.error, pd.DataFrame)

        # TODO: FIXME

        df1 = pd.DataFrame(fp, columns=['x', 'y'])
        df2 = pd.DataFrame(tp.T[:, :2], columns=['x', 'y'])
        slopes = utils.calculate_slope(df1, df2)

        F.refine(arr=slopes)

        self.assertTrue(False)

        # This should raise an error.
        F.refine()
        self.assertIsInstance(F.error, pd.DataFrame)
+7 −4
Original line number Diff line number Diff line
@@ -180,7 +180,7 @@ class FundamentalMatrix(TransformationMatrix):
            compute this homography
    """

    def refine(self, method=ps.esda.mapclassify.Fisher_Jenks, bin_id=0, **kwargs):
    def refine(self, method=ps.esda.mapclassify.Fisher_Jenks, df=None, bin_id=0, **kwargs):
        """
        Refine the fundamental matrix by accepting some data classification
        method that accepts an ndarray and returns an object with a bins
@@ -214,10 +214,12 @@ class FundamentalMatrix(TransformationMatrix):
               data in the new fundamental matrix.
        """
        # Perform the data classification
        fj = method(self.error.values.ravel(), **kwargs)
        if df is None:
            df = self.error
        fj = method(df.values.ravel(), **kwargs)
        bins = fj.bins
        # Mask the data that falls outside the provided bins
        mask = self.error['Reprojection Error'] <= bins[bin_id]
        mask = df <= bins[bin_id]
        new_x1 = self.x1.iloc[mask[mask == True].index]
        new_x2 = self.x2.iloc[mask[mask == True].index]
        fmatrix, new_mask = compute_fundamental_matrix(new_x1.values, new_x2.values)
@@ -225,7 +227,8 @@ class FundamentalMatrix(TransformationMatrix):

        # Update the current state
        self[:] = fmatrix
        self.mask[self.mask == True] = mask
    #    self.mask[self.mask == True] = mask
        self.mask = mask

        # Update the action stack
        try:
+167 −0
Original line number Diff line number Diff line
%% Cell type:markdown id: tags:

This notebook demonstrates a test of autocnet on the New Horizons LORRI data

%% Cell type:code id: tags:

``` python
import os
import sys
sys.path.insert(0, os.path.abspath('..'))

import unittest

from autocnet.examples import get_path
from autocnet.fileio.io_controlnetwork import to_isis
from autocnet.fileio.io_controlnetwork import write_filelist
from autocnet.graph.network import CandidateGraph
from autocnet.fileio import utils

#%pylab inline
%pylab qt4
```

%% Cell type:code id: tags:

``` python
serial_numbers = {'AS15-M-0295_SML.png': '1971-07-31T01:24:11.754',
                'AS15-M-0296_SML.png': '1971-07-31T01:24:36.970',
                'AS15-M-0297_SML.png': '1971-07-31T01:25:02.243',
                'AS15-M-0298_SML.png': '1971-07-31T01:25:27.457',
                'AS15-M-0299_SML.png': '1971-07-31T01:25:52.669',
                'AS15-M-0300_SML.png': '1971-07-31T01:26:17.923'}

for k, v in serial_numbers.items():
    serial_numbers[k] = 'APOLLO15/METRIC/{}'.format(v)


```

%% Cell type:code id: tags:

``` python
adjacency = get_path('two_image_adjacency.json')
basepath = get_path('Apollo15')
cg = CandidateGraph.from_adjacency(adjacency, basepath=basepath)

cg.extract_features(method='sift', extractor_parameters={"nfeatures":500})
cg.match_features(k=2)
```

%% Cell type:code id: tags:

``` python
for source, destination, edge in cg.edges_iter(data=True):
    # Perform the symmetry check
    edge.symmetry_check()
    # Perform the ratio test
    edge.ratio_check(clean_keys=['symmetry'])
```

%% Cell type:code id: tags:

``` python
cg.apply_func_to_edges("compute_fundamental_matrix", clean_keys=['symmetry', 'ratio'])
```

%% Cell type:code id: tags:

``` python
f = cg.edge[0][1].fundamental_matrix
f
```

%% Cell type:code id: tags:

``` python
len((f.x2.y.values - f.x1.y.values)/(f.x2.x.values - f.x1.x.values))
```

%% Cell type:code id: tags:

``` python
df=utils.calculate_slope(f.x1, f.x2)
df.values.ravel()
```

%% Cell type:code id: tags:

``` python
f.mask[f.mask==True]
```

%% Cell type:code id: tags:

``` python
f.refine(df=utils.calculate_slope(f.x1, f.x2))
```

%% Cell type:code id: tags:

``` python
f.rollback()
```

%% Cell type:code id: tags:

``` python
f.mask
```

%% Cell type:code id: tags:

``` python
figsize(18,18)
fig, ax = plt.subplots(1,1)
ax = cg.edge[0][1].plot(clean_keys=['ratio', 'fundamental'], ax=ax)
```

%% Cell type:code id: tags:

``` python
figsize(18,18)
fig, ax = plt.subplots(1,1)
ax = cg.edge[0][2].plot(clean_keys=['ratio', 'symmetry', 'fundamental', 'subpixel'], ax=ax)
```

%% Cell type:code id: tags:

``` python

        for source, destination, edge in cg.edges_iter(data=True):

            # Perform the symmetry check
            edge.symmetry_check()
            self.assertIn(edge.masks['symmetry'].sum(), range(400, 600))

            # Perform the ratio test
            edge.ratio_check(clean_keys=['symmetry'])
            self.assertIn(edge.masks['ratio'].sum(), range(40, 100))

        # Step: Compute the homographies and apply RANSAC
        cg.apply_func_to_edges("compute_homography", clean_keys=['symmetry', 'ratio'])

        # Step: Compute the overlap ratio and coverage ratio
        for s, d, edge in cg.edges_iter(data=True):
            edge.coverage_ratio(clean_keys=['symmetry', 'ratio'])

        # Step: Compute subpixel offsets for candidate points
        cg.apply_func_to_edges("subpixel_register", clean_keys=['ransac'])

        # Step: And create a C object
        cnet = cg.to_cnet(clean_keys=['symmetry', 'ratio', 'ransac', 'subpixel'])

        # Step: Create a fromlist to go with the cnet and write it to a file
        filelist = cg.to_filelist()
        write_filelist(filelist, path="fromlis.lis")

        # Step update the serial numbers
        nid_to_serial = {}
        for i, node in cg.nodes_iter(data=True):
            nid_to_serial[i] = self.serial_numbers[node.image_name]

        cnet.replace({'nid': nid_to_serial}, inplace=True)
        # Step: Output a control network
        to_isis('TestTwoImageMatching.net', cnet, mode='wb',
                networkid='TestTwoImageMatching', targetname='Moon')
```