build scene tree from images

def build_tree(self, directory):
        '''build scene tree from images'''
        confile = os.path.join(directory, 'config.yml')
        conf = {}
        if os.path.exists(confile):
            conf = yaml.load(open(confile).read())

        class node(defaultdict):
            name = ''
            parent = None
            tmpl = None
            rect = None
            mask = None

            def __str__(self):
                obj = self
                names = []
                while obj.parent is not None:
                    names.append(obj.name)
                    obj = obj.parent
                return '-'.join(names[::-1])

        def tree():
            return node(tree)

        root = tree()
        for s in os.listdir(directory):
            if not s.endswith('.png') or s.endswith('_mask.png'): 
                continue
            obj = root
            for i in s[:-4].split('-'):
                obj[i].name = i
                obj[i].parent = obj
                obj = obj[i]
            obj.tmpl = cv2.imread(os.path.join(directory, s))
            obj.rect = conf.get(s[:-4], {}).get('rect')
            maskimg = conf.get(s[:-4], {}).get('mask')
            if maskimg is not None:
                maskimg = os.path.join(directory, maskimg)
                if os.path.exists(maskimg):
                    obj.mask = cv2.imread(maskimg)

        self.tree = root
        self.current_scene = []
        self.confile = confile
        self.conf = conf