繁体   English   中英

线性有向无环图

[英]Linear Directed Acyclic Graph

我有一个OCR任务,在该任务中图像过度分割。 现在,我想构建一个数据结构(各种有向无环图)以获取图像的所有可能组合。

例:
这张照片

我首先将其分为四个部分,a [3],b [4的左半部分],c [4的右半部分],d [2]。 现在,我将对它们进行各种组合。 要获得以下路径。

0)a,b,c,d(基本配置)

1)a,bc,d(正确的配置)

2)ab,c,d

3)a,b,cd

等等

我正在寻找在Python中实现这一点。 是否有现有的软件包? 如果不是,最好的数据结构是什么? DAG最近吗? 有各种各样的DAG效果更好吗?

谢谢,

好,我有一个答案。 可以这样实现。

import random

def combine(wt1, wt2):
    return random.random() < .1, (wt1+wt2)//2

class Linetree():
    def __init__(self, wts):
        self.nodes = []
        for i, wt in enumerate(wts):
            self.nodes.append([[i+1, wt]])

        self.nodes.append([])
        self.processed = []
        self.checked = []

    def processnode(self, idx):
        if idx in self.processed:
            return

        ichild = 0
        while ichild < len(self.nodes[idx]):
            chidx, chwt = self.nodes[idx][ichild]
            self.processnode(chidx)

            igrandchild = 0
            while igrandchild < len(self.nodes[chidx]):
                grchidx, grchwt = self.nodes[chidx][igrandchild]
                if (idx, grchidx) in self.checked:
                    igrandchild += 1
                    continue

                tocombine, newwt = combine(chwt, grchwt)
                self.checked.append((idx, grchidx))
                if tocombine:
                    self.nodes[idx].append([grchidx, newwt])

                igrandchild += 1
            ichild += 1
        self.processed.append(idx)

    def build(self):
        self.processnode(0)

    def get_paths(self, n=0):
        if len(self.nodes[n]) == 0:
            yield [n]

        for ch, wt in self.nodes[n]:
            for sub_path in self.get_paths(ch):
                yield [n] + sub_path

    def pathwt(self, path):
        ret = 0
        for i in range(len(path)-1):
            for child, wt in self.nodes[path[i]]:
                if child == path[i+1]:
                    ret += wt
                    break
            else:
                raise ValueError(str(path))

        return ret

    def __str__(self):
        ret = ""
        for i, children in enumerate(self.nodes):
            ret += "\nNode {}: ".format(i)
            for child in children:
                ret += "{}, ".format(child)
        return ret

def main():
    wts = range(10, 80, 10)
    print(list(enumerate(wts)))
    lt = Linetree(wts)
    print(lt.nodes)
    print(lt)
    lt.build()
    print(lt)

    paths = lt.get_paths()
    for path in paths:
        print(path, lt.pathwt(path))

main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM