Exemple #1
0
    def __init__(self, args):
        rospy.init_node('roadmap_server')
        self.optimization_distance = rospy.get_param('~optimization_distance', 10);
        
        self.tf = TransformListener()
        stereo_cam = camera.Camera((389.0, 389.0, 89.23 * 1e-3, 323.42, 323.42, 274.95))
        self.skel = Skeleton(stereo_cam)
        # self.skel.node_vdist = 1
        if False:
          self.skel.load(args[1])
          self.skel.optimize()
          self.startframe = 100000
        else:
          self.startframe = 0

        self.frame_timestamps = {}
        self.vo = None

        self.pub = rospy.Publisher("roadmap", vslam.msg.Roadmap)

        time.sleep(1)
        #self.send_map(rospy.time(0))
        self.wheel_odom_edges = set()

        rospy.Subscriber('/wide_stereo/raw_stereo', stereo_msgs.msg.RawStereo, self.handle_raw_stereo, queue_size=2, buff_size=7000000)
 def init(self):
     pygame.init()
     self.skeleton = Skeleton(self)
     self._init_surface()
     self.screen_lock = thread.allocate()
     self._init_screen()
     self._init_kinect()
Exemple #3
0
def main():
    points = list(pcd.read('david2/pcd/david2_1317518872.840330800.pcd'))
    sk = Skeleton(boneData())
    skBones = sk.Bones()
    segments = dict((key,[]) for key in skBones.keys()) # setup
    for p in points:
        minDist = 1e20 # big
        bestBone = 'T' # torso by default
        for bName,bone in skBones.iteritems(): # for all bones
            src,dst = bone
            boneDir = subtract(dst, src)
            offset = subtract(p, src)
            dist = crossNormSqr(boneDir,offset)/dot(offset,offset)
            if dist < minDist:
                minDist = dist
                bestBone = bName
        
        if sqrt(minDist) < 10:
            segments[bestBone].append(p)
    
    f = open('segmented.obj', 'w')
    for segName,points in segments.iteritems():
        print segName, len(points)
        if segName in ('LE2H', 'RE2H', 'LK2F', 'RK2F'):
            color = (1,0,0)
        elif segName in ('LS2E', 'RS2E', 'LH2K', 'RH2K'):
            color = (0,1,0)
        elif segName == 'T':
            color = (0,0,1)
        elif segName == 'N2H':
            color = (0,1,1)
        for p in points:
            col = blend(p[3:], color, 0.25) # tint
            f.write('v %f %f %f %f %f %f\n'%(p[0],p[1],p[2],col[0],col[1],col[2]))
Exemple #4
0
def CreateScene(pSdkManager, pScene, files):
        
    lSceneInfo = KFbxDocumentInfo.Create(pSdkManager, "SceneInfo")
    lSceneInfo.mTitle = "Body scan"
    lSceneInfo.mSubject = "A body scan"
    lSceneInfo.mAuthor = "Team KinectOpenNiRosBoostGraphLibDaiPclEigen"
    lSceneInfo.mRevision = "rev. 0.1"
    lSceneInfo.mKeywords = "body mesh rigged"
    lSceneInfo.mComment = "no comments"
    pScene.SetSceneInfo(lSceneInfo)

    import os,glob
    
    skelFiles = glob.glob(os.path.dirname(files['skeleton'])+'/*.yaml')
    skelFiles.sort()
    print 'starting export'
    baseSkeletonData = Skeleton.fromFunnyYaml(skelFiles[0])
    print 'imported skeleton'
    lMeshNode,T,V = CreateMesh(pSdkManager, files['obj'])
    pScene.GetRootNode().AddChild(lMeshNode)
    print 'converted mesh'
    CreateSkeletonNodes(pSdkManager, "Skeleton", baseSkeletonData)
    pScene.GetRootNode().AddChild(baseSkeletonData.torsoNode)
    return
    print 'created skeleton'
    LinkMeshToSkeleton(lSdkManager, lMeshNode, baseSkeletonData, files['weights'])
    print 'added skin'
    print 'now adding animation (slow)'
    skels = [(int(fname[-10:-5])/15.,Skeleton.fromFunnyYaml(fname)) for fname in skelFiles[1:]]
    print 'imported all skeletons'
    AnimateSkeleton(pSdkManager, pScene, baseSkeletonData, skels)
    print 'animated skeleton'
    
    return True
Exemple #5
0
def produceFile(skeletonFile, i):
    from skeleton import Skeleton
    skId, scId, scFile = matches[i]
    skel = Skeleton(skeletonFile[skId])
    outputName = 'david2/viz/' + str(skId) + '.obj'

    print outputName
    f = open(outputName, 'w')
    # skeleton geom
    for part in jointNames:
        pos = skel.GetPos(part)
        if pos:
            f.write('v %f %f %f 1 0 0\n' % (pos[0], pos[1], pos[2]))
        else:
            f.write('v nan nan nan 1 0 0\n')
    for row in readPcd('david2/pcd/' + scFile, Skeleton.scale):
        f.write('v %f %f %f %f %f %f\n' % row)
    # skeleton connectivity
    f.write("""f 1 2 3
f 1 3 4
f 1 3 5
f 3 4 6
f 4 6 8
f 3 5 7
f 5 7 9
f 3 1 10
f 3 1 11
f 10 12 14
f 11 13 15
    """)
    f.close()
Exemple #6
0
    def __init__(self,
                 data_root,
                 max_seq_len,
                 delta_len,
                 n_breakpoints=0,
                 speed_range=[1, 1],
                 acc_range=[-1, 1],
                 train=True,
                 remove_static_joints=True,
                 mode='train'):
        # Set arguments
        self.data_root = osp.abspath(osp.expanduser(data_root))
        self.max_seq_len = max_seq_len
        self.delta_len = delta_len
        self.speed_range = speed_range
        self.n_breakpoints = n_breakpoints
        self.acc_range = acc_range
        self.remove_static_joints = remove_static_joints
        self.train = train
        self.subseq_len = self.delta_len * 2
        self.skeleton = Skeleton(
            parents=[
                -1, 0, 1, 2, 3, 4, 0, 6, 7, 8, 9, 0, 11, 12, 13, 14, 12, 16,
                17, 18, 19, 20, 19, 22, 12, 24, 25, 26, 27, 28, 27, 30
            ],
            joints_left=[6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22, 23],
            joints_right=[1, 2, 3, 4, 5, 24, 25, 26, 27, 28, 29, 30, 31])
        assert mode in [
            'train', 'test'
        ], 'Invalid mode for Human36mDataset. Must be \'train\' or \'test\'.'
        self.mode = mode

        # Read dataset
        self.raw_data = read_human36m(self.data_root, self.mode)

        # Reformat data
        self.data = reformat_data(self.raw_data)

        # Filter out sequence that is shorter than `max_seq_len`
        self.data['pose']['3d'] = list(
            filter(lambda x: x.shape[0] >= self.max_seq_len,
                   self.data['pose']['3d']))
        self.data['pose']['2d'] = list(
            filter(lambda x: x.shape[0] >= self.max_seq_len,
                   self.data['pose']['2d']))

        # Remove static joints
        if self.remove_static_joints:
            # Bring the skeleton to 17 joints instead of the original 32
            self.remove_joints(
                [4, 5, 9, 10, 11, 16, 20, 21, 22, 23, 24, 28, 29, 30, 31])

            # Rewire shoulders to the correct parents
            self.skeleton._parents[11] = 8
            self.skeleton._parents[14] = 8

        # Preprocess data; NOTE: make sure index of pivot joint is correct, if used.
        align_and_normalize_dataset_v2(self.data)
Exemple #7
0
    def __init__(self, id, skel_cap, depth_generator):
        self.id = id
        self.skeleton = Skeleton(self, skel_cap, depth_generator)

        self.depth = 0
        self.face = None
        self.image_path = ''

        self.choose_image()
def exportSkel(obj, filename):

    skeleton = Skeleton()
    skeleton.update(obj)

    f = open(filename, 'w')
    
    writeJoint(f, skeleton.root)
    
    f.close()
Exemple #9
0
def exportSkel(obj, filename):

    skeleton = Skeleton()
    skeleton.update(obj)

    f = open(filename, 'w')

    writeJoint(f, skeleton.root)

    f.close()
Exemple #10
0
 def __init__(self, size=(800,800), types={'blue':BLUE},num_cells=10,fps=0):
     Skeleton.__init__(self, size=size, fill= WHITE,fps=fps)
     self.tipos= types
     wrldsize=(size[0]-100-CELL_W/2,size[1]) #-right_GUI-sprite_width/2
     self.world = Objects.World(wrldsize,tipos=list(self.tipos.keys()))
     self.world.gamengine=self
     self.world.collisions=True
     self.world.populate(num_cells)
     self.preload_types()
     self.add_functions()
     # asistant various data for user use
     self.values={}
Exemple #11
0
class User:
	def __init__(self, id, skel_cap, depth_generator):
		self.id = id
		self.skeleton = Skeleton(self, skel_cap, depth_generator)

		self.depth = 0
		self.face = None
		self.image_path = ''

		self.choose_image()
	# __init__

	def update(self):
		self.skeleton.update()
	# update

	def draw(self, surface):
		if self.skeleton.status:
			rate = 900/(self.depth-500)
			if rate < 0: rate = 0

			try:
				transformed_image = pygame.transform.scale(self.face, (int(self.face.get_width()*rate), int(self.face.get_height()*rate)))
				surface.blit(transformed_image, (self.skeleton.head[0]-0.5*transformed_image.get_width(), self.skeleton.head[1]-0.3*transformed_image.get_height()))
			except:
				pass
			# try
		# if
	# draw

	def draw_skeleton(self, surface):
		if self.skeleton.status:
			self.skeleton.draw(surface)
	# draw_skeleton

	def choose_image(self, banned_image='none'):
		images = ['forever.png', 'lol.png', 'poker.png', 'spider.png', 'troll.png', 'fuckyeah.png']
		try:
			images.remove(banned_image)
		except:
			pass

		random.shuffle(images)
		self.image_path = images[0]
		self.face = pygame.image.load('images/%s' % self.image_path)
	# choose_image

	def refresh(self):
		self.choose_image(self.image_path)
def exportMd5(obj, filename):
    """
    This function exports MakeHuman mesh and skeleton data to id Software's MD5 format. 
    
    Parameters
    ----------
   
    obj:     
      *Object3D*.  The object whose information is to be used for the export.
    filename:     
      *string*.  The filename of the file to export the object to.
    """

    skeleton = Skeleton()
    skeleton.update(obj)

    f = open(filename, 'w')
    f.write('MD5Version 10\n')
    f.write('commandline ""\n\n')
    f.write('numJoints %d\n' % (skeleton.joints+1)) # Amount of joints + the hardcoded origin below
    f.write('numMeshes %d\n\n' % (1)) # TODO: 2 in case of hair
    f.write('joints {\n')
    f.write('\t"%s" %d ( %f %f %f ) ( %f %f %f )\n' % ('origin', -1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))
    writeJoint(f, skeleton.root)
    f.write('}\n\n')
    f.write('mesh {\n')
    f.write('\tshader "%s"\n' % (basename(obj.texture))) # TODO: create the shader file
    f.write('\n\tnumverts %d\n' % (len(obj.verts)))
    for vert in obj.verts:
        if obj.uvValues:
            face = vert.sharedFaces[0]
            u, v = obj.uvValues[face.uv[face.verts.index(vert)]]
        else:
            u, v = 0, 0
        # vert [vertIndex] ( [texU] [texV] ) [weightIndex] [weightElem]
        f.write('\tvert %d ( %f %f ) %d %d\n' % (vert.idx, u, 1.0-v, vert.idx, 1))
    f.write('\n\tnumtris %d\n' % (len(obj.faces) * 2))
    for face in obj.faces:
        # tri [triIndex] [vertIndex1] [vertIndex2] [vertIndex3]
        f.write('\ttri %d %d %d %d\n' % (face.idx*2, face.verts[2].idx, face.verts[1].idx, face.verts[0].idx))
        f.write('\ttri %d %d %d %d\n' % (face.idx*2+1, face.verts[0].idx, face.verts[3].idx, face.verts[2].idx))
    f.write('\n\tnumweights %d\n' % (len(obj.verts)))
    for vert in obj.verts:
        # TODO: We attach all vertices to the root with weight 1.0, this should become
        # real weights to the correct bones
        # weight [weightIndex] [jointIndex] [weightValue] ( [xPos] [yPos] [zPos] )
        f.write('\tweight %d %d %f ( %f %f %f )\n' % (vert.idx, 0, 1.0, vert.co[0], -vert.co[2], vert.co[1]))
    f.write('}\n\n')
    f.close()
Exemple #13
0
def create():
    if request.post_vars.site:
        post = request.post_vars.site
        from skeleton import Skeleton
        s = Skeleton(post)

    return dict()
Exemple #14
0
def git(force=False):
    """Creates a new git repo for this project"""

    m = 'This will remove the current .git directory, do you want to continue?'
    if force or confirm(m, default=False):
        # remove wordpress-skeleton.git metadata
        local('rm -rf .git')

        # setup a new repository
        local('git init')
        local('cp -f %s .gitignore' % Skeleton.asset('gitignore.sample'))
        local('git add .')
        local('git commit -m "Initial commit."')

        # TODO: create origin? this is probably not needed
        # if os.path.exists('/files/Git/projects/'):
        #     repo = '/files/Git/projects/%s.git' % options['name']
        #     if not os.path.exists(repo):
        #         local('git clone --bare . %s' % repo)
        #     local('git remote add origin %s' % repo)
        #     local('git config branch.master.remote origin')
        #     local('git config branch.master.merge refs/heads/master')
        # else:
        #     print("\nCan't create origin. Skipping")
    else:
        puts('Ok. Nothing was touched!')
Exemple #15
0
def main():
    assert len(sys.argv) >= 4
    pcdFile = sys.argv[1]
    yamlFile = sys.argv[2]
    outputFile = sys.argv[3]
    if len(sys.argv) == 5:
        offset = float(sys.argv[4])/2 # for displaying several together, non overlapping
    else:
        offset = 0
    
    assert pcdFile.endswith('pcd')
    assert yamlFile.endswith('yaml')
    assert outputFile.endswith('obj')
    weightFile = 'temp-weights'
    
    cmd = '../segmentation/build/sharpSegmentation %s %s %s'%(pcdFile,yamlFile,weightFile)
    assert os.system(cmd) == 0
    
    skel = Skeleton.fromFunnyYaml(yamlFile, relative=False)
    # save it so that they all use the same skel
    canonFile = 'canon.pickle'
    if os.path.exists(canonFile):
        canon = pickle.load(open(canonFile,'r'))
    else:
        canon = skel.Duplicate()
        canon.Canonicalize()
        #canon.sk = None #safe?
        pickle.dump(canon, open(canonFile,'w'))
    
    points = list(pcd.read(pcdFile))
    weights = ReadWeights(weightFile)
    
    I = ((1,0,0),(0,1,0),(0,0,1))
    newPoints = [[offset,0,0,r,g,b] for (_,_,_,r,g,b) in points]
    
    if True: # the right code
        for jointName,skin in weights.iteritems():
            src = Frame(skel.GetRot(jointName), skel.GetPos(jointName))
            dst = Frame(I, canon.GetPos(jointName))
            print jointName,src.o,dst.o
            for index,weight in skin:
                plusEq(newPoints[index], mult(absolute(dst, relative(src, points[index])), weight))
    else: # tesing code
        j = 0
        for jointName,skin in weights.iteritems():
            src = Frame(skel.GetRot(jointName), skel.GetPos(jointName))
            dst = Frame(I, canon.GetPos(jointName))
            print jointName,src.o,dst.o
            for index,weight in skin:
                plusEq(newPoints[index], relative(src, points[index]))
                plusEq(newPoints[index], (j,0,0))
            j += 0.5
        
    
    f = open(outputFile, 'w')
    for row in newPoints:
        if row[0] == row[0]:
            f.write('v %f %f %f %f %f %f\n'%tuple(row))
    f.close()
    print 'output to',outputFile
Exemple #16
0
 def __init__(self, video_name):
     self.title_window = "Demonstrateur reconnaissance de personne"
     self.skeletonService = Skeleton()
     self.cap = cv2.VideoCapture(video_name)
     self.opWrapper = op.WrapperPython()
     self.opWrapper.configure(params)
     self.opWrapper.start()
     self.gaitClassifier = GaitClassifier()
     self.last_frame = None
     self.kp_frames = []
     self.stop = False
     w, h = (int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
             int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
     self.out = cv2.VideoWriter(
         "Recording_" + datetime.datetime.now().strftime("%Y%m%d_%H%M%S") +
         ".mp4", cv2.VideoWriter_fourcc(*'MP4V'), 25, (w, h))
Exemple #17
0
def display_skeleton(kinect_node, idx, loader):
    bodies, univ_time = loader.load_body_file(idx)
    skeleton_list = [Skeleton(x) for x in bodies]

    kinect_idx = loader.nearest_depth_idx(univ_time, kinect_node)
    img = loader.load_depth_frame(kinect_node, kinect_idx)

    cmap = plt.get_cmap('jet')
    rgba = cmap(img)
    rgba[:, :, 0] *= 0
    for skeleton in skeleton_list:
        joints = skeleton_2d_points(skeleton, loader, kinect_node)

        edges = []
        for limb in SkeletonLimbs:
            point_a = joints[limb.value[0].value]
            point_b = joints[limb.value[1].value]
            edges.append(((point_a[0], point_a[1]), (point_b[0], point_b[1])))

        mag_map = magnitude_map(img, edges)
        rgba[:, :, 0] += mag_map
        # img = np.multiply(img, mag_map)

    plt.imshow(img, interpolation='nearest', cmap='jet')
    plt.imshow(rgba)
    plt.show()
Exemple #18
0
    def skeletonize(self, thres, binSize=10.0, sigma=5.0):
        """
        Initialise the backbone finding routine. The "backbone" is approximated
        by using a skeletonization algorithm. It will thus find a backbone with
        with branches.
        
        To find the skeleton, the localisations are binned in a 2D histogram,
        blurred by a gaussian and the resulting image is binarized using the
        threshold value. From the binary images pixel at the edges are taken
        away until only the skeleton remains.
        """
        if not self.runCluster:
            print('You need to run the clustering first!')
            return

        self.backbone = Skeleton()
        self.backbone.setData(self.cluster.getResult())
        self.backbone.threshold(thres, binSize=binSize, sigma=sigma)
Exemple #19
0
	def __init__(self, id, skel_cap, depth_generator):
		self.id = id
		self.skeleton = Skeleton(self, skel_cap, depth_generator)

		self.depth = 0
		self.face = None
		self.image_path = ''

		self.choose_image()
Exemple #20
0
    def test_remote_proxy(self):
        machine = GumballMachine(3, 'HZ')
        skeleton = Skeleton(machine)
        monitor = GumballMonitor()
        stub = Stub()

        monitor.set_stub(stub)
        stub.set_skeleton(skeleton)

        monitor.report()
Exemple #21
0
 def __param_init__(self, clean=False):
     try:
         self.dataset.close()
         print('Save h5py ....')
         if clean:
             os.remove(self.kp.dstr + '.h5')
             print('Remove h5py ....')
     except:
         pass
     self.fig = None
     self.kp = Kparam(self.exeno, username)
     # self.movie = movie.Movie(self.exeno)
     self.dtw = Dtw()
     self.denoise = Denoise()
     self.rel = Rel()
     self.io = Dataoutput()
     self.h_mod = Human_model()
     self.skel = Skeleton()
     self.fextr = Finger_extract()
 def __init__(self, category):
     gui3d.TaskView.__init__(self, category, 'Skeleton')
     
     self.status = self.addView(gui3d.TextView(style=gui3d.TextViewStyle._replace(left=10, top=585, zIndex=9.1)))
     
     self.__skeleton = Skeleton()
     self.__skeletonMesh = None
     self.__skeletonObject = None
     
     self.bone = None
Exemple #23
0
def exportSkeleton(obj, filename):
    """
    This function exports joint information describing the structure of the 
    MakeHuman humanoid mesh object in Biovision BVH format. 
    
    Parameters
    ----------
   
    obj:     
      *Object3D*.  The object whose information is to be used for the export.
    filename:     
      *string*.  The filename of the file to export the object to.
    """

    skeleton = Skeleton()
    skeleton.update(obj)

    # Write bvh file

    f = open(filename, 'w')
    f.write('HIERARCHY\n')
    f.write('ROOT ' + skeleton.root.name + '\n')
    f.write('{\n')
    f.write("\tOFFSET	%f  %f  %f\n" %
            (skeleton.root.position[0], skeleton.root.position[1],
             skeleton.root.position[2]))
    f.write(
        '\tCHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n'
    )
    for joint in skeleton.root.children:
        writeJoint(f, joint, 1)
    f.write('}\n')
    f.write('MOTION\n')
    f.write('Frames:    1\n')
    f.write('Frame Time: 0.0\n')
    f.write(" %f  %f  %f" %
            (skeleton.root.position[0], skeleton.root.position[1],
             skeleton.root.position[2]))
    for i in xrange(skeleton.endEffectors):
        f.write(" 0.0000 0.0000 0.0000")
    f.write("\n")
    f.close()
    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'BVH Player')
        
        self.status = self.addView(gui3d.TextView(style=gui3d.TextViewStyle._replace(left=10, top=585, zIndex=9.1)))
        
        self.__skeleton = bvhSkeleton('data/bvhs/03_03.bvh')
        self.__skeleton.updateFrame(-1)
        self.__skeletonMesh = None
        self.__skeletonObject = None
        self.bone = None
        
        self.__humanSkeleton = Skeleton()
        
        self.optionsBox = self.addView(gui3d.GroupBox([10, 80, 9.0], 'Options', gui3d.GroupBoxStyle._replace(height=24+25+36*1+24*2+6)))

        self.frameSlider = self.optionsBox.addView(gui3d.Slider(value = 0, min = 0, max = self.__skeleton.frames, label = 'Frame: %d'))
        self.playPause = self.optionsBox.addView(gui3d.Button("Play"))
        self.showHuman = self.optionsBox.addView(gui3d.ToggleButton("Show human"))
        self.exportFrame = self.optionsBox.addView(gui3d.Button("Export frame"))
        
        @self.frameSlider.event
        def onChanging(value):
            self.__updateSkeletonMesh(value-1)
            self.__updateHumanMesh(self.__humanSkeleton.root)
            gui3d.app.selectedHuman.meshData.update()
            
        @self.frameSlider.event
        def onChange(value):
            self.__updateSkeletonMesh(value-1)
            self.__updateHumanMesh(self.__humanSkeleton.root)
            gui3d.app.selectedHuman.meshData.update()
                
        @self.playPause.event
        def onClicked(value):
            if self.playPause.label.getText() == 'Play':
                self.playPause.label.setText('Pause')
                self.timer = mh.addTimer(max(30, int(self.__skeleton.frameTime * 1000)), self.onFrameChanged)
            else:
                self.playPause.label.setText('Play')
                mh.removeTimer(self.timer)
                
        @self.showHuman.event
        def onClicked(event):
            self.showHuman.setSelected(not self.showHuman.selected)
            if self.showHuman.selected:
                gui3d.app.selectedHuman.show()
                self.getSkeleton().hide()
            else:
                gui3d.app.selectedHuman.hide()
                self.getSkeleton().show()
                
        @self.exportFrame.event
        def onClicked(event):
            self.exportCurrentFrame()
Exemple #25
0
def replace(pattern, replacement):
    """Replace strings in database records"""

    prepare()

    host = options['project.mysql.host']
    db = options['project.mysql.db']
    username = options['project.mysql.user']
    password = options['project.mysql.password']

    path = Skeleton.asset('searchandreplace.php')
    args = (path, pattern, replacement, host, username, password, db)
    local('php %s %s %s %s %s %s %s true' % args)
Exemple #26
0
  def __init__(self, source):
    self.cvim = None

    # These variables are internal:

    self.stereo_cam = source.cam()
    print "Camera is", self.stereo_cam
    self.connected = False
    self.snail_trail = []
    self.source = source
    self.inlier_history = []
    self.label = 0
    self.skel_dist_thresh = 0.5;        # in meters

    # These variables can be tweaked:

    self.fd = FeatureDetectorFast(300)
#    self.fd = FeatureDetectorStar(300)
    self.ds = DescriptorSchemeCalonder(32,16) # set up lower sequential search window
    self.camera_preview = False
    self.vo = VisualOdometer(self.stereo_cam,
                             scavenge = False,
                             position_keypoint_thresh = 0.3,
                             angle_keypoint_thresh = 10*pi/180,
                             inlier_thresh = 100,
                             sba=None,
                             num_ransac_iters=500,
                             inlier_error_threshold = 3.0)
    self.skel = Skeleton(self.stereo_cam,
                         link_thresh = 100,
                         descriptor_scheme = self.ds,
                         optimize_after_addition = False)
    self.skel.node_vdist = 0
    self.running = -1                   # run forever

    if self.camera_preview:
      cv.NamedWindow("Camera")
      cv.MoveWindow("Camera", 0, 700)
Exemple #27
0
def read_csv(filename):
    data = []
    with open(filename, 'r') as reader:
        for line in reader:
            fields = line.split(',')
            fields[len(fields) - 1] = fields[len(fields) - 1].replace('\n', '')
            for i in range(len(fields)):
                data.append(float(fields[i]))

    data = np.array(data).reshape((int)(len(data) / 32 / 3), 32, 3)
    skeletons = []
    for d in data:
        skeletons.append(Skeleton(d))
    return skeletons
 def create_monsters(self):
     monsters = []
     boss = Boss()
     boss.level = self.area_number
     monsters.append(boss)
     skeletons = []
     number_of_skeletons = randrange(2, 5)
     for i in range(number_of_skeletons):
         skeletons.append(Skeleton('Skeleton_' + str(i + 1)))
     skeletons[0].has_key = True
     for skeleton in skeletons:
         skeleton.level = self.area_number
         monsters.append(skeleton)
     return monsters
Exemple #29
0
    def __on_skeleton_changed(self, skeleton_message):
        """ reacts to publishers message by updating the skeletons and
        notifies listeners to create and remove objects accordingly.

        Args:
             skeleton_message (list): [0] skeleton_id (int) and [1] skeleton (Skeleton)
        """

        if len(skeleton_message) < 2:
            return

        skeleton_id = skeleton_message[0]

        if skeleton_message[1] is 'kill':
            # remove
            self.__notify_remove_skeleton(skeleton_id)
            return

        skeleton_joint = skeleton_message[1]
        # print 'joint type: ', skeleton_joint.joint_type

        # check if skeleton id is known
        # if yes - update can be done, just count another change
        if skeleton_id in self.__skeletons and skeleton_id in self.__skeleton_changes:
            self.__skeleton_changes[skeleton_id] += 1
        # if no - create skeleton so that update can be done
        else:
            self.__skeletons[skeleton_id] = Skeleton(skeleton_id)
            self.__skeleton_changes[skeleton_id] = 1

        # add or update joint
        # self.__skeletons[skeleton_id].update_joint(skeleton_joint.joint_type, skeleton_joint)
        self.__skeletons[skeleton_id].update_joint_smooth(
            skeleton_joint.joint_type, skeleton_joint)

        # if number of changes (joints) enough propagate to listeners: (create and) update objects
        # if skeleton_id in self.__skeleton_changes and self.__skeleton_changes[skeleton_id] > 24:
        # use update interval to react only to every Xth change of the skeleton, x = self.update_interval
        if skeleton_id in self.__skeleton_changes \
               and self.__skeleton_changes[skeleton_id] / 25.0 >= self.__update_interval:
            self.__skeleton_changes[skeleton_id] = 0
            # check if skeleton already complete and active before
            if skeleton_id not in self.__active_skeletons:
                self.__notify_create_skeleton(skeleton_id)

            # update listeners on skeleton change
            self.__notify_update_skeleton(skeleton_id)

        self.__reset_lifetime(skeleton_id)
def exportSkeleton(obj, filename):
    """
    This function exports joint information describing the structure of the 
    MakeHuman humanoid mesh object in Biovision BVH format. 
    
    Parameters
    ----------
   
    obj:     
      *Object3D*.  The object whose information is to be used for the export.
    filename:     
      *string*.  The filename of the file to export the object to.
    """

    skeleton = Skeleton()
    skeleton.update(obj)

    # Write bvh file

    f = open(filename, 'w')
    f.write('HIERARCHY\n')
    f.write('ROOT ' + skeleton.root.name + '\n')
    f.write('{\n')
    f.write("\tOFFSET	%f  %f  %f\n" %(skeleton.root.position[0],skeleton.root.position[1],skeleton.root.position[2]))
    f.write('\tCHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n')
    for joint in skeleton.root.children:
        writeJoint(f, joint, 1)
    f.write('}\n')
    f.write('MOTION\n')
    f.write('Frames:    1\n')
    f.write('Frame Time: 0.0\n')
    f.write(" %f  %f  %f" %(skeleton.root.position[0],skeleton.root.position[1],skeleton.root.position[2]) )
    for i in xrange(skeleton.endEffectors):
      f.write(" 0.0000 0.0000 0.0000")
    f.write("\n")
    f.close()
Exemple #31
0
def CreateScene(pSdkManager, pScene, files):

    lSceneInfo = KFbxDocumentInfo.Create(pSdkManager, "SceneInfo")
    lSceneInfo.mTitle = "Body scan"
    lSceneInfo.mSubject = "A body scan"
    lSceneInfo.mAuthor = "Team KinectOpenNiRosBoostGraphLibDaiPclEigen"
    lSceneInfo.mRevision = "rev. 0.1"
    lSceneInfo.mKeywords = "body mesh rigged"
    lSceneInfo.mComment = "no comments"
    pScene.SetSceneInfo(lSceneInfo)

    import os, glob

    skelFiles = glob.glob(os.path.dirname(files['skeleton']) + '/*.yaml')
    skelFiles.sort()
    print 'starting export'
    baseSkeletonData = Skeleton.fromFunnyYaml(skelFiles[0])
    print 'imported skeleton'
    lMeshNode, T, V = CreateMesh(pSdkManager, files['obj'])
    pScene.GetRootNode().AddChild(lMeshNode)
    print 'converted mesh'
    CreateSkeletonNodes(pSdkManager, "Skeleton", baseSkeletonData)
    pScene.GetRootNode().AddChild(baseSkeletonData.torsoNode)
    return
    print 'created skeleton'
    LinkMeshToSkeleton(lSdkManager, lMeshNode, baseSkeletonData,
                       files['weights'])
    print 'added skin'
    print 'now adding animation (slow)'
    skels = [(int(fname[-10:-5]) / 15., Skeleton.fromFunnyYaml(fname))
             for fname in skelFiles[1:]]
    print 'imported all skeletons'
    AnimateSkeleton(pSdkManager, pScene, baseSkeletonData, skels)
    print 'animated skeleton'

    return True
Exemple #32
0
def render(filename, color, theta, dest):
  skel = Skeleton(stereo_cam)
  skel.load(filename, load_PR = False)
  skel.optimize()
  skel.optimize()

  skel.plot(color, False, theta)

  xlim = pylab.xlim()
  ylim = pylab.ylim()
  xrange = xlim[1] - xlim[0]
  yrange = ylim[1] - ylim[0]
  r = max(xrange, yrange) * 0.5 # 0.32
  mid = sum(xlim) / 2
  pylab.xlim(mid - r, mid + r)
  mid = sum(ylim) / 2
  pylab.ylim(mid - r, mid + r)
Exemple #33
0
def run_game():
    # initialize the game and create a screen object using the pygame class. we create an instance screen
    pygame.init()
    screen = pygame.display.set_mode((1000, 600))
    caption = pygame.display.set_caption("skeleton on wood race")
    # set the background colour
    bg_color = (255, 255, 0)
    # create an instance of skeleton
    skeleton = Skeleton(screen)

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                if event.key == pygame.K_RIGHT:
                    # move the skeleton to the right
                    skeleton.moving_right = True
                if event.key == pygame.K_LEFT:
                    skeleton.moving_left = True

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    skeleton.moving_right = False
                if event.key == pygame.K_LEFT:
                    skeleton.moving_left = False

        skeleton.update()
        # redraw the screen during each pass through the loop
        screen.fill(bg_color)
        skeleton.blitme()
        # make the most recently drawn screen visible
        pygame.display.flip()
def train_test_split_observations(ratio, classifier):

    data_dir = Path('..') / 'z'
    clips = []

    # Store Path objects pointing to clipped skeletons
    for root, dirs, files in os.walk(str(data_dir)):
        clips += [ Path(root) / f for f in fnmatch.filter(files, '*clipped*tsv') ]

    # Random split into training and test data
    np.random.shuffle(clips)
    split_pt = int(ratio * len(clips))
    clips_train = clips[:split_pt]
    clips_test = clips[split_pt:]

    O = []
    X = []
    y = []

    for c in clips_train:
        s = Skeleton(str(c))
        s.load(skipheader=False, delimiter='\t', extracols=(232,)) 
        #s.normalize('spine-base')
        X += [ s.data[:,:-1].tolist() ]
        y += [ s.data[:,-1].tolist() ]

    classifier.fit([frame for clip in X for frame in clip ], [ label for clip in y for label in clip ])

    for clip in X:
        O += [ classifier.predict(clip).tolist() ]
        
    O_test = []
    X_test = []
    y_test = []

    for c in clips_test:
        s = Skeleton(str(c))
        s.load(skipheader=False, delimiter='\t', extracols=(232,))
        X_test += [ s.data[:, :-1].tolist() ]
        y_test += [ s.data[:, -1].tolist() ]

    for clip in X_test:
        O_test += [ classifier.predict(clip).tolist() ]

    return (X, y, O, X_test, y_test, O_test)
Exemple #35
0
def init_simul(filename, test_num, cbr_num=50, div_step=1):
    data = read_data_skeleton(filename)
    # test_num, data = interval_compasation(data, test_num, div_step)
    test_num = min(test_num, len(data))

    skeletons = []
    for i in range(test_num):
        skeletons.append(Skeleton(data[i]))

    cbr_num = min(test_num, cbr_num)
    cal_skeletons = []
    for i in range(cbr_num):
        cal_skeletons.append(skeletons[i * div_step])

    calibration = Calibration(cal_skeletons)
    lower_init_mean, upper_init_mean = calibration.get_init_mean(0, filename)

    return skeletons, lower_init_mean, upper_init_mean, test_num
Exemple #36
0
def wordpress(version=None):
    """Download latest stable version of WordPress"""

    if version is None:
        basename = 'latest.tar.gz'
    else:
        basename = 'wordpress-%s.tar.gz' % version

    if os.path.exists(os.path.join(os.getcwd(), basename)):
        os.unlink(os.path.join(os.getcwd(), basename))

    local('wget http://wordpress.org/%s' % basename)
    local('tar -xf %s' % basename)
    local('cp -fR wordpress/* .')
    local('rm -rf wordpress')

    local('mkdir -pm 0777 wp-content/uploads')
    local('cp -f %s .htaccess' % Skeleton.asset('htaccess.sample'))

    local('rm %s' % basename)
Exemple #37
0
 def __proceedHuman(self, human, newSkeletons):
     sameSkeletonProb = []  # probability, that human is 'i' skeleton
     bb = getBoundingBox(human)
     minDelta = getMinDelta(bb)
     for skeleton in self.skeletons:
         sameSkeletonProb.append(skeleton.compareSkeleton(human, minDelta))
     if len(sameSkeletonProb) != 0:
         maxProb = max(sameSkeletonProb)
     else:
         maxProb = 0
     if maxProb >= c.probThreshold:  # skeletons are the same human
         i = sameSkeletonProb.index(maxProb)
         self.skeletons[i].updateSkeleton(human, bb)  # update skeleton
         newSkeletons.append(
             self.skeletons[i])  # add skeleton to new skeletons
         self.skeletons.pop(i)  # skeleton cannot be compared again
     else:
         newSkeletons.append(Skeleton(
             human, self.lastSkeletonId,
             bb))  # make new skeleton if there is no similar skeleton
         self.lastSkeletonId = self.lastSkeletonId + 1
Exemple #38
0
    def _initialize_sprites(self, level_room):

        for y in range(15):
            for x in range(20):
                cell = level_room[y][x]
                normalized_x = x * self.cell_size
                normalized_y = y * self.cell_size

                if cell == 0:
                    self.floors.add(Cobble(normalized_x, normalized_y))
                elif cell == 1:
                    self.walls.add(Brick(normalized_x, normalized_y))
                elif cell == 2:
                    self.wizard = Wizard(normalized_x, normalized_y)
                    self.floors.add(Cobble(normalized_x, normalized_y))
                elif cell == 3:
                    self.door.add(Door(normalized_x, normalized_y))
                elif cell == 4:
                    self.floors.add(Cobble(normalized_x, normalized_y))
                    self.skeletons.add(Skeleton(normalized_x, normalized_y))

        self.all_sprites.add(self.floors, self.walls, self.wizard, self.door, self.skeletons)
def train_test_split_clips(ratio):
    data_dir = Path('..') / 'z'
    clips = []

    # Store Path objects pointing to clipped skeletons
    for root, dirs, files in os.walk(str(data_dir)):
        clips += [
            Path(root) / f for f in fnmatch.filter(files, '*clipped*tsv')
        ]

    # Random split into training and test data
    np.random.shuffle(clips)
    split_pt = int(ratio * len(clips))
    clips_train = clips[:split_pt]
    clips_test = clips[split_pt:]

    X = []
    y = []

    for c in clips_train:
        s = Skeleton(str(c))
        s.load(skipheader=False, delimiter='\t', extracols=(232, ))
        #s.normalize('spine-base')
        X += s.data[:, :-1].tolist()
        y += s.data[:, -1].tolist()

    X_test = []
    y_test = []

    for c in clips_test:
        s = Skeleton(str(c))
        s.load(skipheader=False, delimiter='\t', extracols=(232, ))
        X_test += s.data[:, :-1].tolist()
        y_test += s.data[:, -1].tolist()

    return (X, y, X_test, y_test)
Exemple #40
0
def CreateScene(pSdkManager, pScene, pSampleFileName):
    
    lSceneInfo = KFbxDocumentInfo.Create(pSdkManager, "SceneInfo")
    lSceneInfo.mTitle = "David skeleton"
    lSceneInfo.mSubject = "Can we import skeleton data?"
    lSceneInfo.mAuthor = "Team KinectOpenNiRosBoostGraphLibDaiPclEigen"
    lSceneInfo.mRevision = "rev. 0.1"
    lSceneInfo.mKeywords = "skeleton openni range scan nite"
    lSceneInfo.mComment = "no particular comments required."
    pScene.SetSceneInfo(lSceneInfo)

    # make all skeletons
    skelFile = yaml.load(open('../recordings/david2/david2_skeleton.yaml','r'))
    skels = [(float(ts),Skeleton(skData)) for ts,skData in sorted(skelFile.iteritems())]
    
    baseSkeleton = skels[0][1]
    CreateSkeletonNodes(pSdkManager, "Skeleton", baseSkeleton)
    
    AnimateSkeleton(pSdkManager, pScene, baseSkeleton, skels[1:])

    pScene.GetRootNode().AddChild(baseSkeleton.torsoNode)
        
    return True
Exemple #41
0
def dataset_summary():
    dataset_folder = io_utils.get_dataset_folder()
    skinning_path = os.path.join(dataset_folder, 'skinning.npy')
    skeleton_path = os.path.join(dataset_folder, 'skeleton.txt')

    print('-- ANIMATION CLIPS --')
    clips = fnmatch.filter(os.listdir(dataset_folder), '*.npz')
    print(clips)
    print('num clips : ' + str(len(clips)))

    print('-- SKINNING --')
    print('skinning file : ' + str(os.path.exists(skinning_path)))

    print('-- SKELETON --')
    print('skeleton file : ' + str(os.path.exists(skeleton_path)))
    skeleton = Skeleton()
    skeleton.load(skeleton_path)
    skeleton.print_root()
    def __getitem__(self, idx):
        begin, end = self.videos[idx]
        files = self.hand[begin:end]
        skls = self.skl[begin:end]
        max_seq = self.max_seq if self.max_seq is not None else len(files)
        images = np.zeros((max_seq, 100, 200, 3)) - 1
        skeletons = []
        if self.spotting:
            labels = np.array(self.labels[begin:end])
            # labels = torch.from_numpy(np.where(labels > 0,1 , 0)).long()
        else:
            labels = torch.tensor([self.labels[begin]] * max_seq).long() - 1
        for i, img_name, skl in zip(range(max_seq), files, skls):
            images[i] = transform.resize(io.imread(img_name), (100, 200),
                                         preserve_range=True).astype(np.uint8)
            skeletons.append(skl)
        while len(skeletons) < max_seq:
            skeletons.append(Skeleton())
        images = self._split_image(images)

        sample = {'images': images, 'skeletons': skeletons, 'labels': labels}
        if self.transform:
            sample = self.transform(sample)
        else:
            sample['skeletons'] = torch.tensor([
                skl.centralize().normalize().get_normalized_representation()
                for skl in sample['skeletons']
            ]).float()
            image = sample['images']
            image = image.reshape(-1, 4, 2, self.output_size[0],
                                  self.output_size[1], 3)
            image = np.transpose(image, (0, 2, 5, 1, 3, 4)).astype(np.float32)
            sample['images'] = torch.from_numpy(image)
            # sample['skeletons'] = torch.tensor([skl.centralize().normalize().vectorize_reduced() for skl in sample['skeletons']]).float()
            # sample['images'] =  torch.from_numpy(sample['images']).float()/255.0,
        return sample
class PoseTaskView(gui3d.TaskView):

  def __init__(self, category):
    gui3d.TaskView.__init__(self, category, 'Pose')      

    self.zone = ""
    self.skeleton = Skeleton()
    self.selectedGroups = []
    self.joint = None
            
    self.box = self.addView(gui3d.GroupBox([10, 80, 9.0], 'Rotation', gui3d.GroupBoxStyle._replace(height=25+36*3+4+24*3+6)))

    self.Xslider = self.box.addView(gui3d.Slider(value = 0.0, min = -180.0, max = 180.0, label = "RotX: %d"))
    self.Yslider = self.box.addView(gui3d.Slider(value = 0.0, min = -180.0, max = 180.0, label = "RotY: %d"))
    self.Zslider = self.box.addView(gui3d.Slider(value = 0.0, min = -180.0, max = 180.0, label = "RotZ: %d"))
    
    self.skin = self.box.addView(gui3d.CheckBox("Skin", False))
    
    self.resetPoseButton = self.box.addView(gui3d.Button("Reset"))
    self.savePoseButton = self.box.addView(gui3d.Button("Save"))
    self.testButton = self.box.addView(gui3d.Button("Test"))
    
    #get bindings for r-shoulder-joint
    f = open("utils/makepose/r-shoulder-joint.txt")
    #f = open("utils/makepose/test.txt")
    self.jointVerts = []
    self.bindedFaces = None
    
    while (1): 
      line = f.readline()
      if not line: break 
      self.jointVerts.append(int(line));
    f.close()           
    
    self.tets = None

    #get prejoint points to create cage from
    f = open("utils/makepose/r-clavicle.txt")
    self.preJointVerts = []
    while (1): 
      line = f.readline()
      if not line: break 
      self.preJointVerts.append(int(line));
    f.close()
    f = open("utils/makepose/r-scapula.txt") 
    while (1): 
      line = f.readline()
      if not line: break 
      self.preJointVerts.append(int(line));
    f.close()
    
    #get faces of the verts... (for volume preservation)
    
    self.preTets = None
    self.tets1 = None
    self.tets2 = None
    
    @self.testButton.event
    def onClicked(event):
        self.test()

    
    @self.savePoseButton.event
    def onClicked(event):
        exportObj(gui3d.app.selectedHuman.meshData, os.path.join(mh.getPath('exports'), "posed.obj"))

    @self.resetPoseButton.event
    def onClicked(event):
        self.reset()

    @self.Xslider.event
    def onChange(value):
        if self.joint:
            rotation = [value - self.joint.rotation[0], 0.0, 0.0]
            self.joint.rotation[0] = value
            self.rotateJoint(self.joint, self.joint.position, rotation)
            gui3d.app.selectedHuman.meshData.calcNormals()
            gui3d.app.selectedHuman.meshData.update()
                
    @self.Yslider.event
    def onChange(value):
        if self.joint:
            rotation = [0.0, value - self.joint.rotation[1], 0.0]
            self.joint.rotation[1] = value
            self.rotateJoint(self.joint, self.joint.position, rotation)
            gui3d.app.selectedHuman.meshData.calcNormals()
            gui3d.app.selectedHuman.meshData.update()
        
    @self.Zslider.event
    def onChange(value):
        if self.joint:
            rotation = [0.0, 0.0, value - self.joint.rotation[2]]
            self.joint.rotation[2] = value
            self.rotateJoint(self.joint, self.joint.position,rotation)
            gui3d.app.selectedHuman.meshData.calcNormals()
            gui3d.app.selectedHuman.meshData.update()
                  
  def onMouseMoved(self, event):
    if not self.joint:
      human = gui3d.app.selectedHuman
      groups = []
      self.zone = self.getJointZones(event.group.name)

      if self.zone:
        for g in human.mesh.faceGroups:
          if self.zone != "torso":
            if self.zone in g.name:
              groups.append(g)
          elif (self.zone in g.name) and not g.name.endswith("clavicle"):
            groups.append(g)

        for g in self.selectedGroups:
          if g not in groups:
            g.setColor([255, 255, 255, 255])

        for g in groups:
          if g not in self.selectedGroups:
            g.setColor([0, 169, 184, 255])
            
        self.selectedGroups = groups
        gui3d.app.redraw()
  
  def onMouseUp(self, event):
      if self.joint: 
          self.joint = None
      else:
          self.joint = self.skeleton.getJoint(zonesToJointsMapping.get(self.zone))
          if self.joint:
              self.Xslider.setValue(self.joint.rotation[0])
              self.Yslider.setValue(self.joint.rotation[1])
              self.Zslider.setValue(self.joint.rotation[2])
  
  #todo: use a reference on human so we know if we need to compute this on every onShow
  def onShow(self, event):
      gui3d.app.selectedHuman.storeMesh()
      self.skeleton.update(gui3d.app.selectedHuman.meshData)         
      
      #compute bounding box
      #must do this! because mh human changes after the init -_-
      bboxj = calcBBox(gui3d.app.selectedHuman.meshData.verts, self.jointVerts)
      
      #compute right shoulder joint position because we cannot rely on the diamond
      pos = vmul(vadd(bboxj[0],bboxj[1]),0.5)
      self.skeleton.getJoint('joint-r-shoulder').position = pos
      
      #new technique!
      #two cages between the joint instead of the joint in the middle of a single cage
      #get bindings for r-shoulder-joint
      f = open("utils/makepose/2cage-test.txt")
      self.jointVerts = []
      while (1): 
        line = f.readline()
        if not line: break 
        self.jointVerts.append(int(line));
      f.close()
      
      self.bindedFaces = module3d.getFacesFromVerts(self.jointVerts,gui3d.app.selectedHuman.meshData.verts)

      bboxj = calcBBox(gui3d.app.selectedHuman.meshData.verts, self.jointVerts)
      """
      #for the new test we dont add any offset yet
      #adding offset
      bboxj[0][0]= bboxj[0][0] - 0.01
      bboxj[1][0]= bboxj[1][0] + 0.01
      bboxj[0][1]= bboxj[0][1] - 0.01
      bboxj[1][1]= bboxj[1][1] + 0.01
      bboxj[0][2]= bboxj[0][2] - 0.01
      bboxj[1][2]= bboxj[1][2] + 0.01
      """

      bboxj1 = [bboxj[0][:], bboxj[1][:]]
      bboxj1[1][0] = pos[0]
      #print "bboxj1", bboxj1
      self.tets1 =  box2Tetrahedrons(bboxj1)
      bboxj2 = [bboxj[0][:], bboxj[1][:]]
      bboxj2[0][0] = pos[0]
      #print "bboxj2", bboxj2
      self.tets2 =  box2Tetrahedrons(bboxj2)
      #print "bboxj: ", bboxj
      
      
      #computing prejoint bounding box
      #bboxpre = calcBBox(gui3d.app.selectedHuman.meshData.verts, self.preJointVerts)
      #bboxpre[1][0] = min(bboxpre[1][0], bboxj[0][0])
      #print "bboxpre: ", bboxpre
      #self.preTets =  box2Tetrahedrons(bboxpre)
      
      gui3d.TaskView.onShow(self, event)

  def onHide(self, event):
      gui3d.app.selectedHuman.restoreMesh()
      gui3d.app.selectedHuman.meshData.update()
      gui3d.TaskView.onHide(self, event)
      
  def getJointZones(self, groupName):
      for k in jointZones:
          if k in groupName:
              return k
      return None
   
  def rotateJoint(self, joint, center, rotation, transform=None):                
    src = gui3d.app.selectedHuman.meshStored
    dst = gui3d.app.selectedHuman.meshData.verts
    cage = None
    if not transform:
      transform = euler2matrix(vmul(rotation,degree2rad), "sxyz")
      #transform2 = euler2matrix(vmul(self.joint.rotation,degree2rad), "sxyz")
    elif rotation:
      joint.position = vadd(mtransform(transform, vsub(joint.position, center)),center)
      
    if (joint == self.joint) and self.skin.selected and (joint.name == 'joint-r-shoulder'):
      #transform2 = euler2matrix(vmul(self.joint.rotation,degree2rad), "sxyz")
      #tets2 = deformTets(self.tets, center, transform2)
      cages  = deform2Cages([self.tets1,self.tets2], center, self.joint.rotation, 0.5)
      #preJointRot = [0.0,0.0,0.0]
      
      #tets = self.tets + self.preTets
      tets = self.tets1 + self.tets2
      tets2 = cages[0] + cages[1]
      
      #jointVerts = self.jointVerts + self.preJointVerts
      #for i in jointVerts:
      for i in self.jointVerts:
        #using all 10 tetrahedrons as controls
        weights = computeAllWeights(src[i],tets)
        v = [0.0,0.0,0.0]
        """
        for tet_i in xrange(0,5):
          for j in xrange(0,4):
            v= vadd(vmul(tets2[tet_i][j],weights[tet_i][j]),v)
        for tet_i in xrange(0,5):
          for j in xrange(0,4):
            v= vadd(vmul(self.preTets[tet_i][j],weights[tet_i+5][j]),v)
        
        #average of 10 tetrahedrons
        dst[i].co = vmul(v, 0.1)
        """
        for tet_i in xrange(0,10):
          for j in xrange(0,4):
            v= vadd(vmul(tets2[tet_i][j],weights[tet_i][j]),v)
        dst[i].co = vmul(v, 0.1)
        
        """
        #using all 5 tetrahedrons as controls
        weights = computeAllWeights(src[i],self.tets)
        v = [0.0,0.0,0.0]
        for tet_i in xrange(0,5):
          for j in xrange(0,4):
            v= vadd(vmul(tets2[tet_i][j],weights[tet_i][j]),v)
        #average of 5 tetrahedrons
        dst[i].co = vmul(v, 0.2)
        #end of using 5
        """
        
        """
        #using only one tetrahedron as control
        j,w = computeWeights(src[i], self.tets)
        if not j: print src[i]
        v = [0.0,0.0,0.0]
        for k in xrange(0,4):
          v= vadd(vmul(tets2[j][k],w[k]),v)
        dst[i].co = v[:]
        #end of using 1
        """

    for i in joint.bindedVects:
      if (i not in self.jointVerts):
        dst[i].co = vadd(mtransform(transform, vsub(dst[i].co, center)),center)
    
    for child in joint.children:
      self.rotateJoint(child, center, rotation, transform)
  
  def reset(self):
    self.Xslider.setValue(0.0)
    self.Yslider.setValue(0.0)
    self.Zslider.setValue(0.0)
    if self.joint:
      rotation = [-self.joint.rotation[2],-self.joint.rotation[1],-self.joint.rotation[0]]
      self.joint.rotation = [0.0,0.0,0.0]
      transform = euler2matrix(vmul(rotation,degree2rad), "szyx")
      #self.joint.rotation = [0.0,0.0,0.0]
      self.rotateJoint(self.joint, self.joint.position,None, transform)
      gui3d.app.selectedHuman.meshData.calcNormals()
      gui3d.app.selectedHuman.meshData.update()
      
    gui3d.app.redraw()
      
  def test(self):
    pass
class SkeletonView(gui3d.TaskView):

    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'Skeleton')
        
        self.status = self.addView(gui3d.TextView(style=gui3d.TextViewStyle._replace(left=10, top=585, zIndex=9.1)))
        
        self.__skeleton = Skeleton()
        self.__skeletonMesh = None
        self.__skeletonObject = None
        
        self.bone = None
            
    def onShow(self, event):

        gui3d.TaskView.onShow(self, event)
        
        human = gui3d.app.selectedHuman
        
        human.hide()
        self.getSkeleton().show()
        self.__updateSkeletonMesh(human)
        
    def onHide(self, event):

        gui3d.TaskView.onHide(self, event)
        
        gui3d.app.selectedHuman.show()
        self.getSkeleton().hide()
        
    def getSkeleton(self):
        
        human = gui3d.app.selectedHuman
        
        if not self.__skeletonObject:
            
            self.__buildSkeletonMesh(human)
            self.__skeletonObject = self.addObject(gui3d.Object(human.getPosition(), self.__skeletonMesh))
            
        else:
            
            self.__skeletonObject.setPosition(human.getPosition())
        
        self.__skeletonObject.setRotation(human.getRotation())
        
        return self.__skeletonObject
        
    def __buildSkeletonMesh(self, human):
           
        self.__skeleton.update(human.meshData)
        self.__skeletonMesh = module3d.Object3D('skeleton')
        
        self.__skeletonMesh.uvValues = []
        self.__skeletonMesh.indexBuffer = []

        self.__buildBoneMesh(self.__skeleton.root)
        
        self.__skeletonMesh.setCameraProjection(0)
        self.__skeletonMesh.setShadeless(0)
        self.__skeletonMesh.setSolid(0)
        self.__skeletonMesh.calcNormals()
        self.__skeletonMesh.updateIndexBuffer()
        
    def __buildBoneMesh(self, joint):
         
        #self.__addCube(self.__skeletonMesh, joint.position, aljabr.vlen(joint.offset) / 10.0, joint.name.replace('joint', 'bone'))
        if joint.parent:
            position = [joint.transform[3],joint.transform[7],joint.transform[11]]
            parentPosition = [joint.parent.transform[3],
                              joint.parent.transform[7],
                              joint.parent.transform[11]]
            self.__addPrism(self.__skeletonMesh, position, parentPosition, joint.name.replace('joint', 'bone'))
        
        for child in joint.children:
            self.__buildBoneMesh(child)
            
    def __updateSkeletonMesh(self, human):
        
        self.__skeleton.update(human.meshData)
            
        index = 0
        self.__updateBoneMesh(self.__skeleton.root, index)
        
        self.__skeletonMesh.calcNormals()
        self.__skeletonMesh.update()
        
    def __updateBoneMesh(self, joint, index):
        
        if joint.parent:
            self.__updatePrism(self.__skeletonMesh, joint.parent.position, joint.position, index)
            index += 6
        
        for child in joint.children:
            index = self.__updateBoneMesh(child, index)
            
        return index
            
    def __addPrism(self, mesh, o=[0.0, 0.0, 0.0], e=[0.0, 1.0, 0.0], name='prism'):
            
        fg = mesh.createFaceGroup(name)

        dir = aljabr.vsub(e, o) # direction vector from o to e
        len = aljabr.vlen(dir) # distance from o to e
        scale = len * 0.1 # the thickness is 10% of the length
        i = aljabr.vadd(o, aljabr.vmul(dir, 0.25)) # the thickest part is 25% from o
        n = aljabr.vmul(dir, 1.0 / len) # the normalized direction
        q = aljabr.axisAngleToQuaternion(n, pi / 2.0) # a quaternion to rotate the point p1 to obtain the other points
        p1 = aljabr.randomPointFromNormal(n) # a random point in the plane defined by 0,0,0 and n
        p1 = aljabr.vmul(aljabr.vnorm(p1), scale) # the point scaled to the thickness
        p2 = aljabr.quaternionVectorTransform(q, p1) # the other points
        p3 = aljabr.quaternionVectorTransform(q, p2)
        p4 = aljabr.quaternionVectorTransform(q, p3)
        
        p1 = aljabr.vadd(i, p1) # translate by i since we were working in the origin
        p2 = aljabr.vadd(i, p2)
        p3 = aljabr.vadd(i, p3)
        p4 = aljabr.vadd(i, p4)

        # The 6 vertices
        v = []
        v.append(mesh.createVertex(o))      # 0             0
        v.append(mesh.createVertex(p1))     # 1            /|\
        v.append(mesh.createVertex(p2))     # 2           /.2.\
        v.append(mesh.createVertex(p3))     # 3          1` | `3
        v.append(mesh.createVertex(p4))     # 4          \`.4.`/ 
        v.append(mesh.createVertex(e))      # 5           \ | /
                                            #              \|/
                                            #               5
        
        # The 8 faces
        fg.createFace((v[0], v[1], v[4], v[0]))
        fg.createFace((v[0], v[4], v[3], v[0]))
        fg.createFace((v[0], v[3], v[2], v[0]))
        fg.createFace((v[0], v[2], v[1], v[0]))
        fg.createFace((v[5], v[4], v[1], v[5]))
        fg.createFace((v[5], v[1], v[2], v[5]))
        fg.createFace((v[5], v[2], v[3], v[5]))
        fg.createFace((v[5], v[3], v[4], v[5]))
            
    def __addCube(self, mesh, position=[0.0, 0.0, 0.0], scale=1.0, name='cube'):
            
        fg = mesh.createFaceGroup(name)

        # The 8 vertices
        v = []
        v.append(mesh.createVertex(aljabr.vadd(position, [-scale, -scale, -scale]))) # 0         /0-----1\
        v.append(mesh.createVertex(aljabr.vadd(position, [scale, -scale, -scale])))  # 1        / |     | \
        v.append(mesh.createVertex(aljabr.vadd(position, [scale, scale, -scale])))   # 2       |4---------5|
        v.append(mesh.createVertex(aljabr.vadd(position, [-scale, scale, -scale])))  # 3       |  |     |  |
        v.append(mesh.createVertex(aljabr.vadd(position, [-scale, -scale, scale])))  # 4       |  3-----2  |  
        v.append(mesh.createVertex(aljabr.vadd(position, [scale, -scale, scale])))   # 5       | /       \ |
        v.append(mesh.createVertex(aljabr.vadd(position, [scale, scale, scale])))    # 6       |/         \|
        v.append(mesh.createVertex(aljabr.vadd(position, [-scale, scale, scale])))   # 7       |7---------6|
        
        # The 6 faces
        fg.createFace((v[4], v[5], v[6], v[7])) # front
        fg.createFace((v[1], v[0], v[3], v[2])) # back
        fg.createFace((v[0], v[4], v[7], v[3])) # left
        fg.createFace((v[5], v[1], v[2], v[6])) # right
        fg.createFace((v[0], v[1], v[5], v[4])) # top
        fg.createFace((v[7], v[6], v[2], v[3])) # bottom
        
    def __updatePrism(self, mesh, o, e, index):
            
        dir = aljabr.vsub(e, o) # direction vector from o to e
        len = aljabr.vlen(dir) # distance from o to e
        scale = len * 0.1 # the thickness is 10% of the length
        i = aljabr.vadd(o, aljabr.vmul(dir, 0.25)) # the thickest part is 25% from o
        n = aljabr.vmul(dir, 1.0 / len) # the normalized direction
        q = aljabr.axisAngleToQuaternion(n, pi / 2.0) # a quaternion to rotate the point p1 to obtain the other points
        p1 = aljabr.randomPointFromNormal(n) # a random point in the plane defined by 0,0,0 and n
        p1 = aljabr.vmul(aljabr.vnorm(p1), scale) # the point scaled to the thickness
        p2 = aljabr.quaternionVectorTransform(q, p1) # the other points
        p3 = aljabr.quaternionVectorTransform(q, p2)
        p4 = aljabr.quaternionVectorTransform(q, p3)
        
        p1 = aljabr.vadd(i, p1) # translate by i since we were working in the origin
        p2 = aljabr.vadd(i, p2)
        p3 = aljabr.vadd(i, p3)
        p4 = aljabr.vadd(i, p4)

        # The 6 vertices
        mesh.verts[index].co = o
        mesh.verts[index+1].co = p1
        mesh.verts[index+2].co = p2
        mesh.verts[index+3].co = p3
        mesh.verts[index+4].co = p4
        mesh.verts[index+5].co = e
        
    def onMouseDragged(self, event):
        
        gui3d.app.selectedHuman.show()
        self.getSkeleton().hide()
        
        gui3d.TaskView.onMouseDragged(self, event)
            
        gui3d.app.selectedHuman.hide()
        self.getSkeleton().show()
        
    def onMouseWheel(self, event):
        
        gui3d.app.selectedHuman.show()
        self.getSkeleton().hide()
        
        gui3d.TaskView.onMouseWheel(self, event)
            
        gui3d.app.selectedHuman.hide()
        self.getSkeleton().show()
        
    def onMouseEntered(self, event):
        
        gui3d.TaskView.onMouseEntered(self, event)
        
        self.bone = event.group
        self.bone.setColor([0, 255, 0, 255])
        self.status.setText(event.group.name)
        gui3d.app.redraw()

    def onMouseExited(self, event):
        
        gui3d.TaskView.onMouseExited(self, event)
        
        self.bone.setColor([255, 255, 255, 255])
        self.status.setText('')
        gui3d.app.redraw()
        
    def onMouseMoved(self, event):
        
        gui3d.TaskView.onMouseMoved(self, event)
        
        if self.bone != event.group:
            self.bone.setColor([255, 255, 255, 255])
            self.bone = event.group
            self.bone.setColor([0, 255, 0, 255])
            self.status.setText(event.group.name)
        gui3d.app.redraw()
        
    def onResized(self, event):
        
        self.status.setPosition([10, event.height-15, 9.1])
Exemple #45
0
pygame.init()

FRAME_TIME = 50 #50ms is 20 frames per second

if __name__ == '__main__':
    print("Starting Pumpkin Hero...")
    screen_vars = ScreenVars()
    screen = pygame.display.set_mode((screen_vars.get_width(), screen_vars.get_height()))

    black = (0,0,0)

    witch = Witch(50,0,75,75)
    zombie = Zombie(250,0,75,75)
    monster = Monster(450,0,75,75)
    skeleton = Skeleton(650,0,75,75)

    done = False
    last_time = time.time()*1000.0
    SPEED = 5
    game = Game()
    key_monitor = KeyMonitor()

    #Message pump
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_q:
                done = True
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and game.started()==False:
  def __init__(self, category):
    gui3d.TaskView.__init__(self, category, 'Pose')      

    self.zone = ""
    self.skeleton = Skeleton()
    self.selectedGroups = []
    self.joint = None
            
    self.box = self.addView(gui3d.GroupBox([10, 80, 9.0], 'Rotation', gui3d.GroupBoxStyle._replace(height=25+36*3+4+24*3+6)))

    self.Xslider = self.box.addView(gui3d.Slider(value = 0.0, min = -180.0, max = 180.0, label = "RotX: %d"))
    self.Yslider = self.box.addView(gui3d.Slider(value = 0.0, min = -180.0, max = 180.0, label = "RotY: %d"))
    self.Zslider = self.box.addView(gui3d.Slider(value = 0.0, min = -180.0, max = 180.0, label = "RotZ: %d"))
    
    self.skin = self.box.addView(gui3d.CheckBox("Skin", False))
    
    self.resetPoseButton = self.box.addView(gui3d.Button("Reset"))
    self.savePoseButton = self.box.addView(gui3d.Button("Save"))
    self.testButton = self.box.addView(gui3d.Button("Test"))
    
    #get bindings for r-shoulder-joint
    f = open("utils/makepose/r-shoulder-joint.txt")
    #f = open("utils/makepose/test.txt")
    self.jointVerts = []
    self.bindedFaces = None
    
    while (1): 
      line = f.readline()
      if not line: break 
      self.jointVerts.append(int(line));
    f.close()           
    
    self.tets = None

    #get prejoint points to create cage from
    f = open("utils/makepose/r-clavicle.txt")
    self.preJointVerts = []
    while (1): 
      line = f.readline()
      if not line: break 
      self.preJointVerts.append(int(line));
    f.close()
    f = open("utils/makepose/r-scapula.txt") 
    while (1): 
      line = f.readline()
      if not line: break 
      self.preJointVerts.append(int(line));
    f.close()
    
    #get faces of the verts... (for volume preservation)
    
    self.preTets = None
    self.tets1 = None
    self.tets2 = None
    
    @self.testButton.event
    def onClicked(event):
        self.test()

    
    @self.savePoseButton.event
    def onClicked(event):
        exportObj(gui3d.app.selectedHuman.meshData, os.path.join(mh.getPath('exports'), "posed.obj"))

    @self.resetPoseButton.event
    def onClicked(event):
        self.reset()

    @self.Xslider.event
    def onChange(value):
        if self.joint:
            rotation = [value - self.joint.rotation[0], 0.0, 0.0]
            self.joint.rotation[0] = value
            self.rotateJoint(self.joint, self.joint.position, rotation)
            gui3d.app.selectedHuman.meshData.calcNormals()
            gui3d.app.selectedHuman.meshData.update()
                
    @self.Yslider.event
    def onChange(value):
        if self.joint:
            rotation = [0.0, value - self.joint.rotation[1], 0.0]
            self.joint.rotation[1] = value
            self.rotateJoint(self.joint, self.joint.position, rotation)
            gui3d.app.selectedHuman.meshData.calcNormals()
            gui3d.app.selectedHuman.meshData.update()
        
    @self.Zslider.event
    def onChange(value):
        if self.joint:
            rotation = [0.0, 0.0, value - self.joint.rotation[2]]
            self.joint.rotation[2] = value
            self.rotateJoint(self.joint, self.joint.position,rotation)
            gui3d.app.selectedHuman.meshData.calcNormals()
            gui3d.app.selectedHuman.meshData.update()
class BvhView(gui3d.TaskView):

    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'BVH Player')
        
        self.status = self.addView(gui3d.TextView(style=gui3d.TextViewStyle._replace(left=10, top=585, zIndex=9.1)))
        
        self.__skeleton = bvhSkeleton('data/bvhs/03_03.bvh')
        self.__skeleton.updateFrame(-1)
        self.__skeletonMesh = None
        self.__skeletonObject = None
        self.bone = None
        
        self.__humanSkeleton = Skeleton()
        
        self.optionsBox = self.addView(gui3d.GroupBox([10, 80, 9.0], 'Options', gui3d.GroupBoxStyle._replace(height=24+25+36*1+24*2+6)))

        self.frameSlider = self.optionsBox.addView(gui3d.Slider(value = 0, min = 0, max = self.__skeleton.frames, label = 'Frame: %d'))
        self.playPause = self.optionsBox.addView(gui3d.Button("Play"))
        self.showHuman = self.optionsBox.addView(gui3d.ToggleButton("Show human"))
        self.exportFrame = self.optionsBox.addView(gui3d.Button("Export frame"))
        
        @self.frameSlider.event
        def onChanging(value):
            self.__updateSkeletonMesh(value-1)
            self.__updateHumanMesh(self.__humanSkeleton.root)
            gui3d.app.selectedHuman.meshData.update()
            
        @self.frameSlider.event
        def onChange(value):
            self.__updateSkeletonMesh(value-1)
            self.__updateHumanMesh(self.__humanSkeleton.root)
            gui3d.app.selectedHuman.meshData.update()
                
        @self.playPause.event
        def onClicked(value):
            if self.playPause.label.getText() == 'Play':
                self.playPause.label.setText('Pause')
                self.timer = mh.addTimer(max(30, int(self.__skeleton.frameTime * 1000)), self.onFrameChanged)
            else:
                self.playPause.label.setText('Play')
                mh.removeTimer(self.timer)
                
        @self.showHuman.event
        def onClicked(event):
            self.showHuman.setSelected(not self.showHuman.selected)
            if self.showHuman.selected:
                gui3d.app.selectedHuman.show()
                self.getSkeleton().hide()
            else:
                gui3d.app.selectedHuman.hide()
                self.getSkeleton().show()
                
        @self.exportFrame.event
        def onClicked(event):
            self.exportCurrentFrame()
                
    def onFrameChanged(self):
        
        frame = self.frameSlider.getValue() + 1
        
        if frame > self.frameSlider.max:
            frame = 1
            
        self.frameSlider.setValue(frame)
        self.__updateSkeletonMesh(frame-1)
        gui3d.app.redraw()
        
    def exportCurrentFrame(self):
        
        exportPath = mh.getPath('exports')
        if not os.path.exists(exportPath):
            os.makedirs(exportPath)
             
        mh2obj.exportObj(gui3d.app.selectedHuman.meshData, os.path.join(exportPath, 'bvh_frame_%d.obj' % self.frameSlider.getValue()))
            
    def onShow(self, event):

        gui3d.TaskView.onShow(self, event)
        
        gui3d.app.selectedHuman.hide()
        self.getSkeleton().show()
        
        gui3d.app.selectedHuman.storeMesh()
        self.__humanSkeleton.update(gui3d.app.selectedHuman.meshData)
        
    def onHide(self, event):

        gui3d.TaskView.onHide(self, event)
        gui3d.app.selectedHuman.show()
        self.getSkeleton().hide()
        
        gui3d.app.selectedHuman.restoreMesh()
        gui3d.app.selectedHuman.meshData.calcNormals()
        gui3d.app.selectedHuman.meshData.update()
        
    def getSkeleton(self):
        
        human = gui3d.app.selectedHuman
        
        if not self.__skeletonObject:
            
            self.__buildSkeletonMesh()
            self.__skeletonObject = self.addObject(gui3d.Object(aljabr.vadd(human.getPosition(), [0.0, -20.0, 0.0]), self.__skeletonMesh))
            
        else:
            
            self.__skeletonObject.setPosition(aljabr.vadd(human.getPosition(), [0.0, -20.0, 0.0]))
        
        self.__skeletonObject.setRotation(human.getRotation())
        
        return self.__skeletonObject
        
    def __buildSkeletonMesh(self):
           
        self.__skeletonMesh = module3d.Object3D('skeleton')
        
        self.__skeletonMesh.uvValues = []
        self.__skeletonMesh.indexBuffer = []

        self.__buildBoneMesh(self.__skeleton.root)
        
        self.__skeletonMesh.setCameraProjection(0)
        self.__skeletonMesh.setShadeless(0)
        self.__skeletonMesh.setSolid(0)
        self.__skeletonMesh.calcNormals()
        self.__skeletonMesh.updateIndexBuffer()
        
    def __buildBoneMesh(self, joint):
         
        if joint.parent:
            position = [joint.transform[3],joint.transform[7],joint.transform[11]]
            parentPosition = [joint.parent.transform[3],
                              joint.parent.transform[7],
                              joint.parent.transform[11]]
            joint.p = self.__addPrism(self.__skeletonMesh, parentPosition, position, 'bone-' + joint.name)
            #joint.p = self.__addPrism(self.__skeletonMesh, joint.parent.position, joint.position, 'bone-' + joint.name)
        
        for child in joint.children:
            self.__buildBoneMesh(child)
            
    def __updateSkeletonMesh(self, frame):
        
        self.__skeleton.updateFrame(frame)
            
        index = 0
        self.__updateBoneMesh(self.__skeleton.root, index)
        
        self.__skeletonMesh.calcNormals()
        self.__skeletonMesh.update()

    def __updateHumanMesh(self, joint, src=None, dst=None):
        
        # copy angles
        bvhName = mhToBvhMapping.get(joint.name, '')
        if bvhName:
            bvhJoint = self.__skeleton.getJoint(bvhName)
            joint.rotation = bvhJoint.rotation[:]
        else:
            joint.rotation = [0.0, 0.0, 0.0]
        
        joint.calcTransform(False)
        
        if not src:
            src = gui3d.app.selectedHuman.meshStored
            
        if not dst:
            dst = gui3d.app.selectedHuman.meshData.verts
            
        nsrc = gui3d.app.selectedHuman.meshStoredNormals
            
        for i in joint.bindedVects:
            #dst[i].co = aljabr.mtransform(joint.transform, aljabr.mtransform(joint.inverseTransform, src[i]))
            dst[i].co = aljabr.mtransform(joint.transform, aljabr.vsub(src[i], joint.position))
            dst[i].no = aljabr.mtransform(joint.normalTransform, nsrc[i])
        
        for child in joint.children:
            self.__updateHumanMesh(child, src, dst)
        
      #note: don't do skeleton update
      
    def __updateBoneMesh(self, joint, index):

        if joint.parent:
            position = [joint.transform[3],joint.transform[7],joint.transform[11]]
            parentPosition = [joint.parent.transform[3],
                              joint.parent.transform[7],
                              joint.parent.transform[11]]
            self.__updatePrism(self.__skeletonMesh, parentPosition, position, index, joint.p)
            index += 6
        
        for child in joint.children:
            index = self.__updateBoneMesh(child, index)
            
        return index
            
    def __addPrism(self, mesh, o=[0.0, 0.0, 0.0], e=[0.0, 1.0, 0.0], name='prism'):
            
        fg = mesh.createFaceGroup(name)

        dir = aljabr.vsub(e, o) # direction vector from o to e
        len = aljabr.vlen(dir) # distance from o to e
        scale = 0.5 # the thickness is 10% of the length
        i = aljabr.vadd(o, aljabr.vmul(dir, 0.25)) # the thickest part is 25% from o
        n = aljabr.vmul(dir, 1.0 / len) # the normalized direction
        q = aljabr.axisAngleToQuaternion(n, pi / 2.0) # a quaternion to rotate the point p1 to obtain the other points
        p = p1 = aljabr.randomPointFromNormal(n) # a random point in the plane defined by 0,0,0 and n
        p1 = aljabr.vmul(aljabr.vnorm(p1), scale) # the point scaled to the thickness
        p2 = aljabr.quaternionVectorTransform(q, p1) # the other points
        p3 = aljabr.quaternionVectorTransform(q, p2)
        p4 = aljabr.quaternionVectorTransform(q, p3)
        
        p1 = aljabr.vadd(i, p1) # translate by i since we were working in the origin
        p2 = aljabr.vadd(i, p2)
        p3 = aljabr.vadd(i, p3)
        p4 = aljabr.vadd(i, p4)

        # The 6 vertices
        v = []
        v.append(mesh.createVertex(o))      # 0             0
        v.append(mesh.createVertex(p1))     # 1            /|\
        v.append(mesh.createVertex(p2))     # 2           /.2.\
        v.append(mesh.createVertex(p3))     # 3          1` | `3
        v.append(mesh.createVertex(p4))     # 4          \`.4.`/ 
        v.append(mesh.createVertex(e))      # 5           \ | /
                                            #              \|/
                                            #               5
        
        # The 8 faces
        fg.createFace((v[0], v[1], v[4], v[0]))
        fg.createFace((v[0], v[4], v[3], v[0]))
        fg.createFace((v[0], v[3], v[2], v[0]))
        fg.createFace((v[0], v[2], v[1], v[0]))
        fg.createFace((v[5], v[4], v[1], v[5]))
        fg.createFace((v[5], v[1], v[2], v[5]))
        fg.createFace((v[5], v[2], v[3], v[5]))
        fg.createFace((v[5], v[3], v[4], v[5]))
        
        return p
            
    def __addCube(self, mesh, position=[0.0, 0.0, 0.0], scale=1.0, name='cube'):
            
        fg = mesh.createFaceGroup(name)

        # The 8 vertices
        v = []
        v.append(mesh.createVertex(aljabr.vadd(position, [-scale, -scale, -scale]))) # 0         /0-----1\
        v.append(mesh.createVertex(aljabr.vadd(position, [scale, -scale, -scale])))  # 1        / |     | \
        v.append(mesh.createVertex(aljabr.vadd(position, [scale, scale, -scale])))   # 2       |4---------5|
        v.append(mesh.createVertex(aljabr.vadd(position, [-scale, scale, -scale])))  # 3       |  |     |  |
        v.append(mesh.createVertex(aljabr.vadd(position, [-scale, -scale, scale])))  # 4       |  3-----2  |  
        v.append(mesh.createVertex(aljabr.vadd(position, [scale, -scale, scale])))   # 5       | /       \ |
        v.append(mesh.createVertex(aljabr.vadd(position, [scale, scale, scale])))    # 6       |/         \|
        v.append(mesh.createVertex(aljabr.vadd(position, [-scale, scale, scale])))   # 7       |7---------6|
        
        # The 6 faces
        fg.createFace((v[4], v[5], v[6], v[7])) # front
        fg.createFace((v[1], v[0], v[3], v[2])) # back
        fg.createFace((v[0], v[4], v[7], v[3])) # left
        fg.createFace((v[5], v[1], v[2], v[6])) # right
        fg.createFace((v[0], v[1], v[5], v[4])) # top
        fg.createFace((v[7], v[6], v[2], v[3])) # bottom
        
    def __updatePrism(self, mesh, o, e, index, p):
            
        dir = aljabr.vsub(e, o) # direction vector from o to e
        len = aljabr.vlen(dir) # distance from o to e
        scale = 0.5 # the thickness is 10% of the length
        i = aljabr.vadd(o, aljabr.vmul(dir, 0.25)) # the thickest part is 25% from o
        n = aljabr.vmul(dir, 1.0 / len) # the normalized direction
        q = aljabr.axisAngleToQuaternion(n, pi / 2.0) # a quaternion to rotate the point p1 to obtain the other points
        p1 = p # a random point in the plane defined by 0,0,0 and n
        p1 = aljabr.vmul(aljabr.vnorm(p1), scale) # the point scaled to the thickness
        p2 = aljabr.quaternionVectorTransform(q, p1) # the other points
        p3 = aljabr.quaternionVectorTransform(q, p2)
        p4 = aljabr.quaternionVectorTransform(q, p3)
        
        p1 = aljabr.vadd(i, p1) # translate by i since we were working in the origin
        p2 = aljabr.vadd(i, p2)
        p3 = aljabr.vadd(i, p3)
        p4 = aljabr.vadd(i, p4)

        # The 6 vertices
        mesh.verts[index].co = o
        mesh.verts[index+1].co = p1
        mesh.verts[index+2].co = p2
        mesh.verts[index+3].co = p3
        mesh.verts[index+4].co = p4
        mesh.verts[index+5].co = e
        
    def onMouseDragged(self, event):
      
      gui3d.app.selectedHuman.show()
      self.getSkeleton().hide()
      
      gui3d.TaskView.onMouseDragged(self, event)
      if self.showHuman.selected:
        pass
      else:
        gui3d.app.selectedHuman.hide()
        self.getSkeleton().show()
        
    def onMouseWheel(self, event):
      
      if self.showHuman.selected:
        pass
      else:
        gui3d.app.selectedHuman.show()
        self.getSkeleton().hide()
      
      gui3d.TaskView.onMouseWheel(self, event)
      
      if self.showHuman.selected:
        pass
      else:
        gui3d.app.selectedHuman.hide()
        self.getSkeleton().show()
        
    def onMouseEntered(self, event):
        
        gui3d.TaskView.onMouseEntered(self, event)
        
        if 'bone' in event.group.name:
            self.bone = event.group
            self.bone.setColor([0, 255, 0, 255])
            self.status.setText(event.group.name)
        gui3d.app.redraw()

    def onMouseExited(self, event):
        
        gui3d.TaskView.onMouseExited(self, event)
        
        if self.bone:
            self.bone.setColor([255, 255, 255, 255])
            self.status.setText('')
        gui3d.app.redraw()
        
    def onMouseMoved(self, event):
        
        gui3d.TaskView.onMouseMoved(self, event)
        
        if 'bone' in event.group.name and self.bone != event.group:
            self.bone.setColor([255, 255, 255, 255])
            self.bone = event.group
            self.bone.setColor([0, 255, 0, 255])
            self.status.setText(event.group.name)
        gui3d.app.redraw()
        
    def onResized(self, event):
        
        self.status.setPosition([10, event.height-15, 9.1])
Exemple #48
0
import numpy as np
import copy
from skeleton import Skeleton
from mocap_dataset import MocapDataset
from camera import normalize_screen_coordinates, image_coordinates

h36m_skeleton = Skeleton(
    parents=[
        -1, 0, 1, 2, 3, 4, 0, 6, 7, 8, 9, 0, 11, 12, 13, 14, 12, 16, 17, 18,
        19, 20, 19, 22, 12, 24, 25, 26, 27, 28, 27, 30
    ],
    joints_left=[6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22, 23],
    joints_right=[1, 2, 3, 4, 5, 24, 25, 26, 27, 28, 29, 30, 31])

h36m_cameras_intrinsic_params = [
    {
        'id':
        '54138969',
        'center': [512.54150390625, 515.4514770507812],
        'focal_length': [1145.0494384765625, 1143.7811279296875],
        'radial_distortion':
        [-0.20709891617298126, 0.24777518212795258, -0.0030751503072679043],
        'tangential_distortion':
        [-0.0009756988729350269, -0.00142447161488235],
        'res_w':
        1000,
        'res_h':
        1002,
        'azimuth':
        70,  # Only used for visualization
    },
Exemple #49
0
def init(argv):
  opts, methods = getopt(argv, 'hl:r:vm:s:a:fi:NP:ducS', ['help', 'lang=', 'reference=', 'version' ,'main=', 'skeleton=', 'add=', 'cout', 'force', 'include=', 'prefix=', 'downcase', 'uppercase', 'camel', 'snake'])
  xunit = load()
  includes = []
  prefix = 1
  force = 0
  cout = 0
  add = None
  skeleton = None
  main = None
  lang = None
  downcase = None
  snake = None
  for opt, value in opts:
    if '-h' == opt or '--help' == opt:
      usage()
      sys.exit(0)
    elif '-v' == opt or '--version' == opt:
      version()
      for lang in xunit.lang.items():
        print '  ' + lang[1].version + '(--lang ' + lang[0] + ')'
      sys.exit(0)
    elif '-r' == opt or '--reference' == opt:
      try:
        print xunit.lang[value].reference
      except KeyError:
        sys.stderr.write('Un Support Language:%s' % value)
        sys.exit(1)
    elif '-l' == opt or '--lang' == opt:
      try:
        lang = xunit.lang[value]
      except KeyError:
        sys.stderr.write('Un Support Language:%s' % value)
        sys.exit(1)
    elif '-m' == opt or '--main' == opt:
      main = value
    elif '-s' == opt or '--skeleton' == opt:
      skeleton = value
    elif '-a' == opt or '--add' == opt:
      add = value
      force = 1
    elif '-P' == opt or '--prefix' == opt:
      if value == '+':
        prefix = 1
      elif value == '-':
        prefix = 0
      else:
        raise ValueError, "prefix option can accept only '+' or '-'"
    elif '-f' == opt or '--force' == opt:
      force = 1
    elif '-d' == opt or '--downcase' == opt:
      downcase = 1
    elif '-u' == opt or '--uppercase' == opt:
      downcase = 0
    elif '-S' == opt or '--snake' == opt:
      snake = 1
    elif '-c' == opt or '--camel' == opt:
      snake = 0
    elif '--cout' == opt:
      cout = 1
    elif '-i' == opt or '--include' == opt:
      includes.append(value)
  if add is not None:
    add = Add(add, language(xunit, lang, add), methods, includes)
    add.create()
    output(add.filename, add.result, force, cout)
  else:
    if skeleton is not None:
      skeleton = Skeleton(skeleton, methods, includes, prefix, 
        language(xunit, lang, skeleton))
      skeleton.create()
      output(skeleton.filename, skeleton.result, force, cout)
    if main is not None:
      main = Main(main, language(xunit, lang, main))
      main.create()
      output(main.filename, main.result, force, cout)