Code Monkey home page Code Monkey logo

gco_python's Introduction

pygco

travis status

Python wrappers for GCO alpha-expansion and alpha-beta-swaps. These wrappers provide a high level interface for graph cut inference for multi-label problems.

See my blog for examples and comments: peekaboo-vision.blogspot.com

Installation

With Pip

  • Run pip install git+git://github.com/amueller/gco_python

For Linux

  • Download and install Cython (use your package manager).

  • run make

  • Run example.py for a simple example.

For Windows

  • Make sure Cython is installed (included in enthought Python distribution for example)

  • Download original source from http://vision.csd.uwo.ca/code/gco-v3.0.zip

  • Build gco with your compiler of choice. Create a dynamic library at libgco.so.

  • Adjust the path to gco in setup.py.

  • run python setup.py build.

  • run example.py for a simple example.

Troubleshooting

There have been some problems compiling gco (not my wrappers) using gcc4.7. Please install gcc-4.6 and adjust the call in Makefile accordingly.

Usage

GCO implements alpha expansion and alpha beta swaps using graphcuts. These can be used to efficiently find low energy configurations of certain energy functions. Note that from a probabilistic viewpoint, GCO works in log-space.

Note that all input arrays are assumed to be in int32. This means that float potentials must be rounded!

These algorithms can only deal with certain energies. Unfortunately I have not figured out yet how to convert C++ errors to Python. If an unknown error is raised, it probably means that you used an invalid energy function. Look at the gco README for details.

This package gives a high level interface to gco, providing the following functions:

cut_simple: Graph cut on a 2D grid using a global label affinity-matrix.

cut_VH: NOT DONE YET Graph cut on a 2D grid using a global label affinity-matrix and edge-weights. V contains the weights for vertical edges, H for horizontal ones.

cut_from_graph: Graph cut on an arbitrary graph with global label affinity-matrix.

cut_from_graph_weighted: NOT DONE YET Graph cut on an arbitrary graph with global label affinity-matrix and edgeweights.

See example.py and example_middlebury.py for examples and the gco README for more details.

gco_python's People

Contributors

amueller avatar kunal0895 avatar mjstevens777 avatar narayanschuetz avatar trsaunders avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

gco_python's Issues

Error on windows

Traceback (most recent call last):
  File "example.py", line 3, in <module>
    from pygco import cut_simple, cut_from_graph
ImportError: No module named 'pygco'

Thanks

update setup

Hello, may I have a friendly advice for the setup, you should include also setup require since it may fail while installing to empty environment, you can take an inspiration from the alternative GCO wrapper.

Unable to compile gco

Hello there,

I'm trying to use pygco and I'm stuck in trying to compile it. I tried compiling in both Windows and Ubuntu but with no luck.
Is there a guide on how I should compile the whole folder or which files to compile? I tried starting from GCOptimization but I got too many errors.

Note: I'm using it for a python project where I try to colorize an image by using the graph cut method. My gcc version is 5.4.0

I also tried using pip and it installed pygco=0.0.1 but when I try to import it, it doesn't recognize it.

It gives: No module named 'pygco'

I import it like so:
import pygco

non-symmetric smooth_cost

Hey!

Do you know if unsymmetric smoothness_cost is supported?. The Matlab interface (function GCO_SetSmoothCost) checks for that and raises an error in that case. Some sentences in the GCO_README also suggest that it's not supported.

If that is the case, I suggest adding the check, it will save headaches to future users :-)

Compiling GCO

Hi,

Thanks for the producing the wrapper!

I'm a bit confused about the instruction "Download gco from http://vision.csd.uwo.ca/code/ and compile"

How should gco be compiled? I downloaded "gco-v3.0.zip" but there's no Makefile or obvious way it should be compiled. Am I looking to compile each file or build a static lib or something?

if I just set the gco path and run setup.py build it doesn't go well: http://pastebin.com/XCzCThPV

Sorry if these are obvious questions :)

thanks!

tom

Cannot install with pip3

https://github.com/cgearhart/DepthFromDefocus
This get me here.

I ran

pip3 install git+git://github.com/amueller/gco_python

got these:
Collecting git+git://github.com/amueller/gco_python
Cloning git://github.com/amueller/gco_python to /tmp/pip-x5y6yeo2-build
Collecting cython (from pygco==0.0.1)
Using cached https://files.pythonhosted.org/packages/b2/20/46a78072ecd4fda072c3791a257b03af99b64673671663067d18bc4935ec/Cython-0.29.7-cp36-cp36m-manylinux1_x86_64.whl
Collecting numpy (from pygco==0.0.1)
Using cached https://files.pythonhosted.org/packages/c1/e2/4db8df8f6cddc98e7d7c537245ef2f4e41a1ed17bf0c3177ab3cc6beac7f/numpy-1.16.3-cp36-cp36m-manylinux1_x86_64.whl
Installing collected packages: cython, numpy, pygco
Running setup.py install for pygco ... done
Successfully installed cython-0.29.7 numpy-1.16.3 pygco-0.0.1

However the package is not recognized.

from gco_python.pygco import cut_simple

ModuleNotFoundError: No module named 'gco_python'

Bug?

3-class segmentation

Hello,
may have a question about you wrapper for GraphCut. I found it very nice and compare to other wrapper, this one s most useful.
Btw, My name is Jiří Borovec and I am a PhD student at CTU in Prague and actually I am working on segmentation and registrations so I would like to use this method.
I was testing basic image (see attachment - sample_seg_3cls.jpg) which should be simply segmented into 3 classes. I did following steps:

  1. extract SLIC superpixels
  2. compute colour feature per superpixel
  3. estimate Gaussian Mixture Model (GMM)
  4. assume each component of GMM should be single class so compute probability that each segment belong to each class
    ...so far up to here everything works fine...
  5. construct graph and apply GraphCut
    but it returns only 2-class segmentation (see attachment - figure_1.png). On the other hand, when I take simply maximal a-posteriory probability from step 4) I can get what I would expect (see attachment - figure_2.png) from GraphCut... By my knowledge if I would use zero pairwise potentials the Graph Cut should give the equal results as treasholding by maximal a-posteriory probability, ok?

The part of code I am speaking about is following:
logger.info('Extraction segment connectivity')
vertices, edges = superpixels.makeGraph4Connect(segments)
logger.debug( "Graph connectivity edges: \n" + repr( edges ) )
pairwise = -10 * np.eye(nbCls)
logger.info('Run GraphCut on created graph.')
edges = np.array(edges, dtype=np.int32)
unaries = np.array( (100*prob) , dtype=np.int32)
logger.debug( "Graph unaries potentials: \n" + repr( unaries ) )
pairwise = np.array( pairwise , dtype=np.int32)
logger.debug( "Graph pairwise coefs: \n" + repr( pairwise ) )
resultGraph = cut_from_graph(edges, unaries, pairwise)
logger.debug( "Resulting graph: \n" + repr( resultGraph ) )
In attachment you can find all three files, the main is graphCut.py

Thanks for any advice

sample_seg_3cls
figure_1
figure_2

Segfault in cut_from_graph with specific inputs

(I'm not sure if this is the correct repo to submit this issue. There seem to be 3 versions of the rpo out there, and I don't see an original repo for GCO itself)

I've found a specific set of inputs that causes a segfault in pygco.cut_from_graph.

I wrote a script to demonstrate this and attempt to work down the case to a minimal cause. Unfortunately I've been unable to identify the cause.

However, I did find one (unrelated) easy to fix segfault that happens when you specify an edge index that is out of bounds. This is also in the test script.

The script defines a function for each test case, and then runs them in the main part.
There are several tests for what I thought might be causing the issue, but those ideas turn out to be wrong.

The final test is the smallest version of the error I could reproduce. In this test, removing any of the edges suppresses the error. Then when running with all edges the segfault occurs.


import numpy as np
import pygco


def original_data():
    # Original data that cause segfault
    unary_cost = np.array([[0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0]], dtype=np.int32)

    pairwise_cost = np.array([[-1,  0],
                              [ 0, -1]], dtype=np.int32)

    edges = np.array([[  0,   5, -18],
                      [  0,   6, -19],
                      [  0,   8, -20],
                      [  0,   3, -18],
                      [  0,   1, -21],
                      [  1,   4, -20],
                      [  1,   6, -17],
                      [  1,   7, -20],
                      [  1,   8, -17],
                      [  1,   3,  -1],
                      [  2,   4,   6],
                      [  2,   7, -14],
                      [  2,   1,   0],
                      [  3,   4, -21],
                      [  3,   6, -18],
                      [  3,   8, -20],
                      [  4,   5,   0],
                      [  4,   1,   0],
                      [  5,   4,  24],
                      [  5,   7, -15],
                      [  5,   8,  -2],
                      [  5,   3, -18],
                      [  6,   5,  24],
                      [  6,   4,  -8],
                      [  6,   0,   0],
                      [  6,   8,  24],
                      [  6,   2,  11],
                      [  7,   3,   0],
                      [  7,   4,  14],
                      [  7,   5,   0],
                      [  7,   6,   0],
                      [  7,   8,  29],
                      [  7,   9,  -4],
                      [  8,   4,  15],
                      [  8,   6,   0],  # REMOVING THIS ROW WILL ALSO REMOVE THE SEGFAULT
                      [  8,   2,  19],
                      [  8,   9,   8],
                      [  9,   4,  -5],
                      [  9,   6,  -6],
                      [  9,   2,   2],
                      [  9,   3,   0]], dtype=np.int32)
    return unary_cost, pairwise_cost, edges


def original_case_segfault():
    print('--- TESTING ORIGINAL CASE ---')
    unary_cost, pairwise_cost, edges = original_data()
    cutkw = {'algorithm': 'expansion', 'n_iter': 5}

    # This will sefault.
    print('About to segfault on the original case.')
    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost,
                                    **cutkw)
    print('labeling = %r' % (labeling,))


def original_case_fix():
    print('--- TESTING FIX ORIGINAL CASE ---')
    unary_cost, pairwise_cost, edges = original_data()
    # Try changing to upper triangular
    edge_utri = edges.copy()
    flag = edge_utri.T[0] > edge_utri.T[1]
    edge_utri[flag, 0:2] = edge_utri[flag].T[0:2][::-1].T
    edge_utri = edge_utri[np.lexsort(edge_utri.T[::-1])]
    edge_utri = np.ascontiguousarray(edge_utri)

    # Removing spurious 0 weighted egdges seems to fix it.
    # BUT IT TURN SOUT THIS IS ONLY A SIDE EFFECT
    from collections import defaultdict  # NOQA
    uv_list = edge_utri.T[0:2].T
    groups = defaultdict(list)
    for idx, uv in enumerate(uv_list):
        val = edge_utri[idx, 2]
        # Ah there were duplicates with zero values!
        if val != 0:
            group = groups[tuple(uv.tolist())]
            # Removing them fixes it.
            group.append(val)
            assert len(group) == 1, 'should only ever add to a group once'
        else:
            print('Removed uv = %r' % (uv,))

    edges_fixed = np.array([[u, v, val_[0]] for (u, v), val_ in groups.items()])
    edges_fixed = edges_fixed[np.lexsort(edges_fixed.T[::-1])].astype(np.int32)
    edges_fixed = np.ascontiguousarray(edges_fixed)

    #print('edge_utri =\n%r' % (edge_utri,))
    #print('edges_fixed =\n%r' % (edges_fixed,))

    labeling = pygco.cut_from_graph(edges_fixed, unary_cost, pairwise_cost)
    print('labeling = %r' % (labeling,))


# VERYIFY MINIMAL TEST CASE
def test_zero_duplicate_idea():
    print('--- TESTING ZERO DUPLICATE IDEA (Not the cause) ---')

    unary_cost = np.array([[0, 0],
                           [0, 0]], dtype=np.int32)

    pairwise_cost = np.array([[-1,  0],
                              [ 0, -1]], dtype=np.int32)

    edges = np.array([[  0,   1, -100]], dtype=np.int32)

    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost)

    print('If my idea that having a duplicate edge with a 0 weight caused'
          ' segfaults was right then this would segfault'
          ' but it does not')

    edges = np.array([[  0,   1, -100],
                      [  1,   0,  0]], dtype=np.int32)

    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost)

    edges = np.array([[  0,   1, 100],
                      [  0,   1,  0]], dtype=np.int32)

    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost)
    print('labeling = %r' % (labeling,))
    print('... This idea is not the problem!')


def test_impossible_case_idea():
    print('--- TESTING IMPOSSIBLE CASE IDEA ---')
    unary_cost = np.array([[0, 0],
                           [0, 0],
                           [0, 0]], dtype=np.int32)

    pairwise_cost = np.array([[-1,  0],
                              [ 0, -1]], dtype=np.int32)

    edges = np.array([[  0,   1, -100],
                      [  0,   2, -100]], dtype=np.int32)
    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost)

    edges = np.array([[  0,   1, -100],
                      [  2,   0, -100],
                      [  0,   2, -100]], dtype=np.int32)
    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost)
    print('labeling = %r' % (labeling,))
    print('... This idea is not the problem!')


def unrelated_segfault_case_edge_idx_out_of_bounds():
    print('--- TESTING (UNRELATED) EDGE IDX OUT OF BOUNDS ---')
    unary_cost = np.array([[0, 0],
                           [0, 0]], dtype=np.int32)

    pairwise_cost = np.array([[-1,  0],
                              [ 0, -1]], dtype=np.int32)

    edges = np.empty((0, 3), dtype=np.int32)
    print('Initially works')
    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost)
    print('labeling = %r' % (labeling,))
    print('Add an out of bounds edge and it segfaults')
    edges = np.array([[1, 3]], dtype=np.int32)
    print('ABOUT TO SEGFAULT!')
    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost)


def minimal_case_noclue_why():
    print('--- TESTING MINIMAL SEGFAULT CASE ---')
    unary_cost = np.array([[0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0],
                           [0, 0]], dtype=np.int32)

    pairwise_cost = np.array([[-1,  0],
                              [ 0, -1]], dtype=np.int32)

    print('removing any one of these edges will stop the segfault')
    edges = np.array([[  0,   6, -19],
                      [  1,   6, -17],
                      [  3,   6, -18],
                      [  6,   5,  24],
                      [  6,   4,  -8],
                      [  6,   0,   0],
                      [  6,   8,  24],
                      [  6,   2,  11],
                      [  7,   6,   0],
                      [  8,   6,   0],
                      [  9,   6,  -6]], dtype=np.int32)

    cutkw = {'algorithm': 'expansion', 'n_iter': 5}

    print('Testing by removing each edge.')
    flags = np.ones(len(edges), dtype=np.int)
    for idx in range(len(edges)):
        flags[idx] = 0
        edges_ = edges.compress(flags, axis=0)
        labeling = pygco.cut_from_graph(edges_, unary_cost, pairwise_cost,
                                        **cutkw)
        print('labeling = %r' % (labeling,))

    # This will sefault.
    print('BUT when all edges are included it will segfault')
    print('About to segfault. I dont know why.')
    labeling = pygco.cut_from_graph(edges, unary_cost, pairwise_cost,
                                    **cutkw)
    print('labeling = %r' % (labeling,))


if __name__ == '__main__':

    if False:
        # Test the original case
        original_case_segfault()
    else:
        print('skipping original segfault case')

    # I found a simple fix to the original case that does not alter it
    original_case_fix()

    # I had ideas as to what cause the segfaults but they were wrong
    test_zero_duplicate_idea()
    test_impossible_case_idea()

    if False:
        # Found a SECOND simple segfault case, but probably unrelated
        unrelated_segfault_case_edge_idx_out_of_bounds()
    else:
        print('skipping second segfault case')

    if 1:
        # This is a minimal version of the original case
        minimal_case_noclue_why()
    else:
        print('skipping minimal error case')

Convert Python to C++

Hi, there
I have question related to converting code.
I want to use cut_from_graph in C++.

# Python

refine_labels = cut_from_graph(edges, unaries, pairwise)    #  edges (14956,3), unaries(9999, 15), pairwise (15, 15) 
refine_labels (9999,)
// C++ 
int edges[14956][3];
int unaries[9999][15];
int pairwise[15][15];
int *refined_labels = new int[9999];
GCoptimizationGeneralGraph *gc = new GCoptimizationGeneralGraph(9999, 15);

for (int i = 0; i < 14956; i++)
    gc->setNeighbors(edges[i][0], edges[i][1], edges[i][2]);
gc->setDataCost(*unaries);
gc->setSmoothCost(*pairwise);

gc->expansion(5);

for (int i = 0; i < decimated->GetNumberOfCells(); i++)
    refined_labels[i] = gc->whatLabel(i);

I stored edges, unaries, and pairwise in the same way as Python.
And use cut_from_graph() in C++ using converting code that i refer to cut_from_graph() in gco_python.pyx
The code was executed without error, but the result is not refine.
Is it right to convert the code like this?
Is there anything I missed or made a mistake ?
Please give me some advice... Thanks !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.