コード例 #1
0
ファイル: backends.py プロジェクト: over2sd/minette
def loadRealm(fn = None,recursion = 0):
  """Returns a dict containing the config options in the Minette realm file."""
  maxrecursion = 3
  lines = []
  realm = {}
  realm['realmloaded'] = False
  if fn is None or fn == "":
    print "Could not load realm information. No filename provided!"
    exit(-1)
  realm['realmfile'] = fn
  (found,fn) = findFile(lineno(),fn)
  if not found:
    print " [W] Realm %s not loaded." % fn
    return realm
  lines = readfile(fn)
  for line in lines:
    try:
      line = line.strip()
      if line:
        values = [x.strip() for x in line.split('=')]
        if values[0] != "likerealm":
          realm[values[0]] = values[1] # unlike config, existing realm options WILL be clobbered
        elif recursion < maxrecursion: # likerealm must be first option, or it may clobber options for the parent realm.
          rf = "realms/%s.rlm" % values[1]
          recursion += 1
          realm.update(loadRealm(rf,recursion))
    except Exception as e:
      print "There was an error in the realm file: %s" % e
  fn = realm.get("realmdir","")
  (found,fn) = findFile(lineno(),fn)
  if not found:
    print " [E] Fatal error. Realm directory %s not found!" % fn
    exit(-1)
  realm = validateRealm(realm)
  realm['realmloaded'] = True
  return realm
コード例 #2
0
ファイル: backends.py プロジェクト: over2sd/minette
def loadConfig(fn = None,recursion = 0):
  """Returns a dict containing the config options in the Minette config file."""
  maxrecursion = 3
  lines = []
  global config
  global defaults
  if fn is None:
    fn = "default.cfg" # using 3-letter extension for MSWin compatibility, I hope.
  (found,fn) = findFile(lineno(),fn)
  if not found:
    print " [W] Config %s not loaded." % fn
    if not defaults.get("set",False):
      setDefaults()
    config.update(defaults)
    return config
  lines = readfile(fn)
  for line in lines:
    try:
      line = line.strip()
      if line:
        values = [x.strip() for x in line.split('=')]
        if values[0] != "loadconfig":
          if not config.get(values[0]): config[values[0]] = values[1] # existing options will not be clobbered
        elif recursion < maxrecursion and os.path.exists(values[1]): # loadconfig must be first option, or its options may be ignored.
          recursion += 1
          loadConfig(values[1],recursion)
    except Exception as e:
      print " [E] There was an error in the configuration file: %s" % e
  config['file'] = fn
  config = validateConfig(config)
  config['realmfile'] = ""
  if len(config.get("loadrealm","")) > 0 and recursion <= maxrecursion:
    rf = "realms/%s.rlm" % config['loadrealm']
    realm = loadRealm(rf)
    config.update(realm)
  else:
    config['realmloaded'] = False
  config.update(criticalDefaults())
  return config
コード例 #3
0
import cv2 as cv
import argparse
from common import findFile

parser = argparse.ArgumentParser(
    description='Use this script to run action recognition using 3D ResNet34',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
    '--input',
    '-i',
    help=
    'Path to input video file. Skip this argument to capture frames from a camera.'
)
parser.add_argument('--model', required=True, help='Path to model.')
parser.add_argument('--classes',
                    default=findFile('action_recongnition_kinetics.txt'),
                    help='Path to classes list.')

# To get net download original repository https://github.com/kenshohara/video-classification-3d-cnn-pytorch
# For correct ONNX export modify file: video-classification-3d-cnn-pytorch/models/resnet.py
# change
# - def downsample_basic_block(x, planes, stride):
# -     out = F.avg_pool3d(x, kernel_size=1, stride=stride)
# -     zero_pads = torch.Tensor(out.size(0), planes - out.size(1),
# -                              out.size(2), out.size(3),
# -                              out.size(4)).zero_()
# -     if isinstance(out.data, torch.cuda.FloatTensor):
# -         zero_pads = zero_pads.cuda()
# -
# -     out = Variable(torch.cat([out.data, zero_pads], dim=1))
# -     return out
コード例 #4
0
        feature_mul = feature_B @ feature_A
        feature_mul= np.reshape(feature_mul, (b, h, w, h * w))
        feature_mul = feature_mul.transpose(0, 1, 3, 2)
        correlation_tensor = feature_mul.transpose(0, 2, 1, 3)
        correlation_tensor = np.ascontiguousarray(correlation_tensor)
        return [correlation_tensor]


if __name__ == "__main__":
    if not os.path.isfile(args.gmm_model):
        raise OSError("GMM model not exist")
    if not os.path.isfile(args.tom_model):
        raise OSError("TOM model not exist")
    if not os.path.isfile(args.segmentation_model):
        raise OSError("Segmentation model not exist")
    if not os.path.isfile(findFile(args.openpose_proto)):
        raise OSError("OpenPose proto not exist")
    if not os.path.isfile(findFile(args.openpose_model)):
        raise OSError("OpenPose model not exist")

    person_img = cv.imread(args.input_image)
    ratio = 256 / 192
    inp_h, inp_w, _ = person_img.shape
    current_ratio = inp_h / inp_w
    if current_ratio > ratio:
        center_h = inp_h // 2
        out_h = inp_w * ratio
        start = int(center_h - out_h // 2)
        end = int(center_h + out_h // 2)
        person_img = person_img[start:end, ...]
    else:
コード例 #5
0
ファイル: backxml.py プロジェクト: over2sd/minette
def populateWorld():
  """Looks in the realmdir and makes a list of fileids the program can
  load. Makes worldList a tuple of lists.
  """
  global config
  global worldList
  fn = os.path.join(config['realmdir'],"myrealm.cfg")
  persons = []
  places = []
  cities = []
  states = []
  orgs = []
  # other data types.
  (found,fn) = common.findFile(lineno(),fn)
  if config['uselistfile'] and found:
    print "  Loading worldList from file..."
    lines = []
    try:
      with codecs.open(fn,'rU','utf-8') as conf:
        lines = conf.readlines()
        conf.close()
    except IOError as e:
      print "   Could not open worldlist file: %s" % e
      exit(1)
    for line in lines:
      try:
        line = line.strip()
        if line:
          values = [x.strip() for x in line.split('=')]
          if values[0] == "persons":
            y = values[1]
            persons.extend(y.split(','))
          elif values[0] == "places":
            y = values[1]
            places.extend(y.split(','))
          elif values[0] == "cities":
            y = values[1]
            cities.extend(y.split(','))
          elif values[0] == "states":
            y = values[1]
            states.extend(y.split(','))
          elif values[0] == "orgs":
            y = values[1]
            orgs.extend(y.split(','))
          elif values[0] == "person":
            persons.append(values[1])
          elif values[0] == "place":
            places.append(values[1])
          elif values[0] == "city":
            cities.append(values[1])
          elif values[0] == "state":
            states.append(values[1])
          elif values[0] == "org":
            orgs.append(values[1])
          else:
            print "Unknown type %s found" % values[0]
      except Exception as e:
        print "   There was an error in the configuration file: %s" % e
#  elif not found:
#    print "  Fatal error. Realm directory %s does not exist! Exiting." % config['realmdir']
#    exit(-1)
  else:
    print "  Generating worldList from directory..."
    olist = os.listdir(config['realmdir'])
    nlist = []
    ilist = []
    for i in range(len(olist)):
      if re.search(r'.[Xx][Mm][Ll]$',olist[i]):
        ilist.append(os.path.splitext(olist[i])[0])
        nlist.append(olist[i])
    for i in range(len(nlist)):
      fn = os.path.join(config['realmdir'],nlist[i])
      line = ""; match = -1; lno = 2
      while match == -1 and lno < 6:
        line = getline(fn,lno)
        match = line.find("SYSTEM")
        lno += 1
      match2 = line.find(".dtd")
      if match != -1 and match2 > match:
        match += 8 # trims 'SYSTEM "'
        line = line[match:match2] # trims '.dtd">\n'
        if "person" in line:
          persons.append(ilist[i])
        elif "place" in line:
          places.append(ilist[i])
        elif "city" in line:
          cities.append(ilist[i])
        elif "state" in line:
          states.append(ilist[i])
        elif "org" in line:
          orgs.append(ilist[i])
        else:
          print "Unknown type %s found" % line
  if config['debug'] > 2: print "\nPersons: %s\nPlaces: %s\nCities: %s\nStates: %s\nOrgs: %s\n" % (persons,places,cities,states,orgs)
  worldList['p'] = persons
  worldList['l'] = places
  worldList['c'] = cities
  worldList['s'] = states
  worldList['o'] = orgs
  for key in worldList.keys():
    if len(worldList[key]):
      if not len(worldList[key][0]):
        worldList[key] = []
  for s in worldList['s']:
    pushLoc(s)
  getStateList(0)
  getCityList(0)
  if config['debug'] > 3:
    printPretty(worldList)
    printPretty(placeList)