Example #1
0
import opengm
import numpy

chainLength=5
numLabels=100
numberOfStates=numpy.ones(chainLength,dtype=opengm.label_type)*numLabels
gm=opengm.gm(numberOfStates,operator='adder')
#add some random unaries
for vi in range(chainLength):
   unaryFuction=numpy.random.random(numLabels)
   gm.addFactor(gm.addFunction(unaryFuction),[vi])
#add one 2.order function


f=opengm.differenceFunction(shape=[numLabels]*2,weight=0.1)
print type(f),f
fid=gm.addFunction(f)
#add factors on a chain
for vi in range(chainLength-1):
   gm.addFactor(fid,[vi,vi+1])    


inf = opengm.inference.BeliefPropagation(gm,parameter=opengm.InfParam(steps=40,convergenceBound=0 ,damping=0.9))
inf.infer(inf.verboseVisitor())


print inf.arg()

Example #2
0
 def add_a_function(w):
     return gm.addFunction(opengm.differenceFunction(shape=[2, 2],
                                                     weight=w))
Example #3
0
def denoiseModel(
    img,
    norm                    = 2,
    weight                  = 1.0,
    truncate                = None,
    numLabels               = 256,
    neighbourhood           = 4,
    inpaintPixels           = None,
    randInpaitStartingPoint = False
):
    """
    this function is used to set up a graphical model similar to 
    **Denoising and inpainting problems:** from `Mrf- Benchmark <http://vision.middlebury.edu/MRF/results/ >`_
    
    Args : 
        img           : a grayscale image in the range [0,256)
        norm          : used norm for unaries and 2-order functions (default : 2)
        weight        : weight of 2-order functions (default : 1.0)
        truncate      : Truncate second order function at an given value (defaut : None)
        numLabels     : number of labels for each variable in the graphical model, 
                        set this to a lower number to speed up inference  (default : 255)
        neighbourhood : neighbourhood for the second order functions, so far only 4 is allowed (default : 4)
        inpaintPixels : a tuple of x and y coordinates where no unaries are added
        randInpaitStartingPoint : use a random starting point for all pixels without unaries (default : False)
    """
    shape = img.shape
    if(img.ndim!=2):
        raise RuntimeError("image must be gray")
    if neighbourhood != 4 :
        raise RuntimeError("A neighbourhood other than 4 is not yet implemented")

    # normalize and flatten image
    iMin    = numpy.min(img)
    iMax    = numpy.max(img)
    imgNorm = ((img[:,:]-iMin)/(iMax-iMin))*float(numLabels)
    imgFlat = imgNorm.reshape(-1).astype(numpy.uint64)

    # Set up Grapical Model:
    numVar = int(img.size)
    gm = opengm.gm([numLabels]*numVar,operator='adder')
    gm.reserveFunctions(numLabels,'explicit')
    numberOfPairwiseFactors=shape[0]*(shape[1]-1) + shape[1]*(shape[0]-1)
    gm.reserveFactors(numVar-len(inpaintPixels[0]) + numberOfPairwiseFactors )

    # Set up unaries:
    # - create a range of all possible labels
    allPossiblePixelValues=numpy.arange(numLabels)
    pixelValueRep    = numpy.repeat(allPossiblePixelValues[:,numpy.newaxis],numLabels,1)
    # - repeat [0,1,2,3,...,253,254,255] numVar times
    labelRange = numpy.arange(numLabels,dtype=opengm.value_type)
    labelRange = numpy.repeat(labelRange[numpy.newaxis,:], numLabels, 0)
    unaries = numpy.abs(pixelValueRep - labelRange)**norm
    # - add unaries to the graphical model
    fids=gm.addFunctions(unaries.astype(opengm.value_type))
    # add unary factors to graphical model
    if(inpaintPixels is None):
        for l in xrange(numLabels):
            whereL=numpy.where(imgFlat==l)
            gm.addFactors(fids[l],whereL[0].astype(opengm.index_type))
    else:
        # get vis of inpaint pixels
        ipX  = inpaintPixels[0]
        ipY  = inpaintPixels[1]
        ipVi = ipX*shape[1] + ipY

        for l in xrange(numLabels):
            whereL=numpy.where(imgFlat==l)
            notInInpaint=numpy.setdiff1d(whereL[0],ipVi)
            gm.addFactors(fids[l],notInInpaint.astype(opengm.index_type))

    # add ONE second order function
    f=opengm.differenceFunction(shape=[numLabels,numLabels],norm=2,weight=weight)
    fid=gm.addFunction(f)
    vis2Order=opengm.secondOrderGridVis(shape[0],shape[1],True)
    # add all second order factors
    gm.addFactors(fid,vis2Order)

    # create a starting point
    startingPoint = imgFlat.copy()
    if randInpaitStartingPoint :
        startingPointRandom = numpy.random.randint(0,numLabels,size=numVar).astype(opengm.index_type)

        ipVi = inpaintPixels[0]*shape[1] + inpaintPixels[1]
        for x in ipVi:
            startingPoint[x]=startingPointRandom[x]

    startingPoint[startingPoint==numLabels]=numLabels-1            
    return gm,startingPoint.astype(opengm.index_type)
Example #4
0
def denoiseModel(img,
                 norm=2,
                 weight=1.0,
                 truncate=None,
                 numLabels=256,
                 neighbourhood=4,
                 inpaintPixels=None,
                 randInpaitStartingPoint=False):
    """
    this function is used to set up a graphical model similar to 
    **Denoising and inpainting problems:** from `Mrf- Benchmark <http://vision.middlebury.edu/MRF/results/ >`_
    
    Args : 
        img           : a grayscale image in the range [0,256)
        norm          : used norm for unaries and 2-order functions (default : 2)
        weight        : weight of 2-order functions (default : 1.0)
        truncate      : Truncate second order function at an given value (defaut : None)
        numLabels     : number of labels for each variable in the graphical model, 
                        set this to a lower number to speed up inference  (default : 255)
        neighbourhood : neighbourhood for the second order functions, so far only 4 is allowed (default : 4)
        inpaintPixels : a tuple of x and y coordinates where no unaries are added
        randInpaitStartingPoint : use a random starting point for all pixels without unaries (default : False)
    """
    shape = img.shape
    if (img.ndim != 2):
        raise RuntimeError("image must be gray")
    if neighbourhood != 4:
        raise RuntimeError(
            "A neighbourhood other than 4 is not yet implemented")

    # normalize and flatten image
    iMin = numpy.min(img)
    iMax = numpy.max(img)
    imgNorm = ((img[:, :] - iMin) / (iMax - iMin)) * float(numLabels)
    imgFlat = imgNorm.reshape(-1).astype(numpy.uint64)

    # Set up Grapical Model:
    numVar = int(img.size)
    gm = opengm.gm([numLabels] * numVar, operator='adder')
    gm.reserveFunctions(numLabels, 'explicit')
    numberOfPairwiseFactors = shape[0] * (shape[1] -
                                          1) + shape[1] * (shape[0] - 1)
    gm.reserveFactors(numVar - len(inpaintPixels[0]) + numberOfPairwiseFactors)

    # Set up unaries:
    # - create a range of all possible labels
    allPossiblePixelValues = numpy.arange(numLabels)
    pixelValueRep = numpy.repeat(allPossiblePixelValues[:, numpy.newaxis],
                                 numLabels, 1)
    # - repeat [0,1,2,3,...,253,254,255] numVar times
    labelRange = numpy.arange(numLabels, dtype=opengm.value_type)
    labelRange = numpy.repeat(labelRange[numpy.newaxis, :], numLabels, 0)
    unaries = numpy.abs(pixelValueRep - labelRange)**norm
    # - add unaries to the graphical model
    fids = gm.addFunctions(unaries.astype(opengm.value_type))
    # add unary factors to graphical model
    if (inpaintPixels is None):
        for l in xrange(numLabels):
            whereL = numpy.where(imgFlat == l)
            gm.addFactors(fids[l], whereL[0].astype(opengm.index_type))
    else:
        # get vis of inpaint pixels
        ipX = inpaintPixels[0]
        ipY = inpaintPixels[1]
        ipVi = ipX * shape[1] + ipY

        for l in xrange(numLabels):
            whereL = numpy.where(imgFlat == l)
            notInInpaint = numpy.setdiff1d(whereL[0], ipVi)
            gm.addFactors(fids[l], notInInpaint.astype(opengm.index_type))

    # add ONE second order function
    f = opengm.differenceFunction(shape=[numLabels, numLabels],
                                  norm=2,
                                  weight=weight)
    fid = gm.addFunction(f)
    vis2Order = opengm.secondOrderGridVis(shape[0], shape[1], True)
    # add all second order factors
    gm.addFactors(fid, vis2Order)

    # create a starting point
    startingPoint = imgFlat.copy()
    if randInpaitStartingPoint:
        startingPointRandom = numpy.random.randint(
            0, numLabels, size=numVar).astype(opengm.index_type)

        ipVi = inpaintPixels[0] * shape[1] + inpaintPixels[1]
        for x in ipVi:
            startingPoint[x] = startingPointRandom[x]

    startingPoint[startingPoint == numLabels] = numLabels - 1
    return gm, startingPoint.astype(opengm.index_type)
import opengm
import numpy

chainLength = 5
numLabels = 100
numberOfStates = numpy.ones(chainLength, dtype=opengm.label_type) * numLabels
gm = opengm.gm(numberOfStates, operator='adder')
#add some random unaries
for vi in range(chainLength):
    unaryFuction = numpy.random.random(numLabels)
    gm.addFactor(gm.addFunction(unaryFuction), [vi])
#add one 2.order function

f = opengm.differenceFunction(shape=[numLabels] * 2, weight=0.1)
print type(f), f
fid = gm.addFunction(f)
#add factors on a chain
for vi in range(chainLength - 1):
    gm.addFactor(fid, [vi, vi + 1])

inf = opengm.inference.BeliefPropagation(gm,
                                         parameter=opengm.InfParam(
                                             steps=40,
                                             convergenceBound=0,
                                             damping=0.9))
inf.infer(inf.verboseVisitor())

print inf.arg()