Exemplo n.º 1
0
 def init_patchs_array(self, size):
     self.patchs_array = [[Patch(
         (0, 0), 0, self.noised_image)] * self.denoised_image.height
                          ] * self.denoised_image.width
     # Image width
     for x in range(self.denoised_image.width):
         # Image height
         for y in range(self.denoised_image.height):
             self.patchs_array[x][y] = Patch((x, y), size,
                                             self.noised_image)
Exemplo n.º 2
0
def get_adjuster_settings(romfile: str) -> typing.Tuple[str, bool]:
    if hasattr(get_adjuster_settings, "adjuster_settings"):
        adjuster_settings = getattr(get_adjuster_settings, "adjuster_settings")
    else:
        adjuster_settings = persistent_load().get("adjuster", {}).get("last_settings", {})
    if adjuster_settings:
        import pprint
        import Patch
        adjuster_settings.rom = romfile
        adjuster_settings.baserom = Patch.get_base_rom_path()
        whitelist = {"disablemusic", "fastmenu", "heartbeep", "heartcolor", "ow_palettes", "quickswap",
                     "uw_palettes"}
        printed_options = {name: value for name, value in vars(adjuster_settings).items() if name in whitelist}
        sprite = getattr(adjuster_settings, "sprite", None)
        if sprite:
            printed_options["sprite"] = adjuster_settings.sprite.name
        if hasattr(get_adjuster_settings, "adjust_wanted"):
            adjust_wanted = getattr(get_adjuster_settings, "adjust_wanted")
        else:
            adjust_wanted = input(f"Last used adjuster settings were found. Would you like to apply these? \n"
                                  f"{pprint.pformat(printed_options)}\n"
                                  f"Enter yes or no: ")
        if adjust_wanted and adjust_wanted.startswith("y"):
            adjusted = True
            import AdjusterMain
            _, romfile = AdjusterMain.adjust(adjuster_settings)
        else:
            adjusted = False
            import logging
            if not hasattr(get_adjuster_settings, "adjust_wanted"):
                logging.info(f"Skipping post-patch adjustment")
        get_adjuster_settings.adjuster_settings = adjuster_settings
        get_adjuster_settings.adjust_wanted = adjust_wanted
        return romfile, adjusted
    return romfile, False
Exemplo n.º 3
0
    def __init__(self, parent, channel_levels, num_channels=68):
        frames = (make_frame(parent), make_frame(parent))
        channel_levels[:]=[]
        self.number_labels = []
        for channel in range(1, num_channels+1):

            # frame for this channel
            f = Frame(frames[channel > (num_channels/2)])
            # channel number -- will turn yellow when being altered
            num_lab = Label(f, text=str(channel), width=3, bg='grey40', 
                fg='white', font=stdfont, padx=0, pady=0, bd=0, height=1)
            num_lab.pack(side='left')
            self.number_labels.append(num_lab)

            # text description of channel
            Label(f, text=Patch.get_channel_name(channel), width=8, 
                font=stdfont, anchor='w', padx=0, pady=0, bd=0, 
                height=1, bg='black', fg='white').pack(side='left')

            # current level of channel, shows intensity with color
            l = Label(f, width=3, bg='lightBlue', font=stdfont, anchor='e', 
                      padx=1, pady=0, bd=0, height=1)
            l.pack(side='left')
            colorlabel(l)
            channel_levels.append(l)
            f.pack(side='top')

        self.channel_levels = channel_levels
def adjust(args):
    start = time.perf_counter()
    logger = logging.getLogger('Adjuster')
    logger.info('Patching ROM.')

    if os.path.splitext(args.rom)[-1].lower() == '.bmbp':
        import Patch
        meta, args.rom = Patch.create_rom_file(args.rom)

    if os.stat(args.rom).st_size in (0x200000, 0x400000) and os.path.splitext(
            args.rom)[-1].lower() == '.sfc':
        rom = LocalRom(args.rom, patch=False)
    else:
        raise RuntimeError(
            'Provided Rom is not a valid Link to the Past Randomizer Rom. Please provide one for adjusting.'
        )

    apply_rom_settings(rom, args.heartbeep, args.heartcolor, args.quickswap,
                       args.fastmenu, args.disablemusic, args.sprite,
                       args.ow_palettes, args.uw_palettes)
    path = output_path(f'{os.path.basename(args.rom)[:-4]}_adjusted.sfc')
    rom.write_to_file(path)

    logger.info('Done. Enjoy.')
    logger.debug('Total Time: %s', time.perf_counter() - start)

    return args, path
Exemplo n.º 5
0
	def __init__(self, numPatches):

		### Number Of Patches ###
		self.patches = []
		self.patchDistances = []
		self.numPatches = numPatches
		self.totalArea = 0
		self.completePatches = 0

		# May start right on the first mile. 
		start = rand.randint(0, 2000)

		for i in range(numPatches):

			length = rand.randint(100, 3600)

			### Total Square feet
			self.patches.append(Patch.Patch(start, length))
			self.totalArea += self.patches[i].getArea()

			start += length

			# start has to be at least 100 feet from the previous patch. 
			start += rand.randint(100, 2000) 

		# numPatches - 1: N patches, N - 1 inbetween spaces
		for i in range(numPatches - 1):
			
			nextPatch = self.patches[i + 1]
			previousPatch = self.patches[i]

			self.patchDistances.append(nextPatch.getStart() - previousPatch.getEnd())
Exemplo n.º 6
0
 def stageassub(self):
     """returns the current onstage lighting as a levels
     dictionary, skipping the zeros, and using names where
     possible"""
     levs=self.oldlevels
     
     return dict([(Patch.get_channel_name(i),l) for i,l
                  in zip(range(1,len(levs)+1),levs)
                  if l>0])
Exemplo n.º 7
0
def print_tsv(filename, allchans, subs):
    f = open(filename, "w")
    print >> f, "\t" + "\t".join(allchans)

    for name, levels in subs.items():
        normd = {}
        # nrmalize the names in the sub
        for k, v in levels.items():
            normd[Patch.resolve_name(k)] = v

        print >> f, "%s\t%s" % (name, "\t".join([str(normd.get(c, "")) for c in allchans]))
Exemplo n.º 8
0
def adjust(args):
    start = time.perf_counter()
    logger = logging.getLogger('Adjuster')
    logger.info('Patching ROM.')
    vanillaRom = args.baserom
    if os.path.splitext(args.rom)[-1].lower() == '.bmbp':
        import Patch
        meta, args.rom = Patch.create_rom_file(args.rom)

    if os.stat(args.rom).st_size in (0x200000, 0x400000) and os.path.splitext(
            args.rom)[-1].lower() == '.sfc':
        rom = LocalRom(args.rom, patch=False, vanillaRom=vanillaRom)
    else:
        raise RuntimeError(
            'Provided Rom is not a valid Link to the Past Randomizer Rom. Please provide one for adjusting.'
        )
    palettes_options = {}
    palettes_options['dungeon'] = args.uw_palettes

    palettes_options['overworld'] = args.ow_palettes
    palettes_options['hud'] = args.hud_palettes
    palettes_options['sword'] = args.sword_palettes
    palettes_options['shield'] = args.shield_palettes
    # palettes_options['link']=args.link_palettesvera
    racerom = rom.read_byte(0x180213) > 0

    apply_rom_settings(
        rom,
        args.heartbeep,
        args.heartcolor,
        args.quickswap,
        args.fastmenu,
        args.disablemusic,
        args.sprite,
        palettes_options,
        cutscenespeed=args.cutscenespeed if not racerom else "normal",
        reduceflashing=args.reduceflashing)
    path = output_path(f'{os.path.basename(args.rom)[:-4]}_adjusted.sfc')
    rom.write_to_file(path)

    logger.info('Done. Enjoy.')
    logger.debug('Total Time: %s', time.perf_counter() - start)

    return args, path
Exemplo n.º 9
0
 def initializePatches(self):
     #Instantiate Patches
     #Create a list to hold the patches. We first fill these with
     #zeros to hold the place for each Patch object
     self.patch_dict = {
         i: {
             j: 0
         }
         for i in range(self.rows) for j in range(self.cols)
     }
     for i in range(self.rows):
         for j in range(self.cols):
             #replace zeros with actual Patch objects
             good = "sugar" if i + j >= self.rows else "water"
             self.patch_dict[i][j] = Patch(self, i, j, self.sugarMap[i][j],
                                           good)
     self.empty_patches = RandomDict({(i, j): self.patch_dict[i][j]
                                      for i in range(self.rows)
                                      for j in range(self.cols)})
Exemplo n.º 10
0
 def __init__(self, name, width, height):
     ## Setup the simulator
     ## 1. Create World
     self.world = World(name, width, height)
     self.agents = list()
     ## 2. Fill in salinity and inundation data for each patch
     ## TODO: Get env data from GIS dataset
     for x in range(0, width + 1):
         for y in range(0, height + 1):
             p = Patch(1.0 - 1 / (x + 1), 1.0, 1.0, True)
             self.world.setPatch(x, y, p)
     ## 3. Plant some mangroves
     ## TODO: Get tree location from GIS dataset
     ## TODO: Plant different species of plants
     ## For now, plant trees manually
     for i in range(0, min(width, height) + 1):
         plant = Mangrove(0.5, 0, self.world, i, i)
         self.agents.append(plant)
         self.world.putAgent(i, i, plant)
     self.step = 0  ## No tree death, recruitment or storms for now
Exemplo n.º 11
0
    def initializePatches(self):
        #Instantiate Patches
        #Create a dictionary to hold the patches, organize as grid.
        #We first fill these with zeros as placeh holders
        self.patch_dict = {
            row: {
                col: 0
            }
            for row in range(self.rows) for col in range(self.cols)
        }
        for row in range(self.rows):
            for col in range(self.cols):
                # replace zeros with actual Patch objects
                good = "sugar" if row + col < self.cols else "water"
                self.patch_dict[row][col] = Patch(self, row, col,
                                                  self.sugarMap[row][col],
                                                  good)

    # use RandomDict - O(n) time complexity - for choosing random empty patch
        self.empty_patches = RandomDict({(row, col): self.patch_dict[row][col]
                                         for row in range(self.rows)
                                         for col in range(self.cols)})
Exemplo n.º 12
0
async def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'diff_file',
        default="",
        type=str,
        nargs="?",
        help='Path to a Berserker Multiworld Binary Patch file')
    parser.add_argument('--snes',
                        default='localhost:8080',
                        help='Address of the QUsb2snes server.')
    parser.add_argument('--connect',
                        default=None,
                        help='Address of the multiworld host.')
    parser.add_argument('--password',
                        default=None,
                        help='Password of the multiworld host.')
    parser.add_argument(
        '--loglevel',
        default='info',
        choices=['debug', 'info', 'warning', 'error', 'critical'])
    parser.add_argument(
        '--founditems',
        default=False,
        action='store_true',
        help='Show items found by other players for themselves.')
    args = parser.parse_args()

    logging.basicConfig(format='%(message)s',
                        level=getattr(logging, args.loglevel.upper(),
                                      logging.INFO))

    if args.diff_file:
        import Patch
        meta, romfile = Patch.create_rom_file(args.diff_file)
        args.connect = meta["server"]
        logging.info(f"Wrote rom file to {romfile}")
        asyncio.create_task(run_game(romfile))

    ctx = Context(args.snes, args.connect, args.password, args.founditems)

    input_task = asyncio.create_task(console_loop(ctx))

    await snes_connect(ctx, ctx.snes_address)

    if ctx.server_task is None:
        ctx.server_task = asyncio.create_task(server_loop(ctx))

    watcher_task = asyncio.create_task(game_watcher(ctx))

    await ctx.exit_event.wait()
    ctx.server_address = None
    ctx.snes_reconnect_address = None

    await watcher_task

    if ctx.socket is not None and not ctx.socket.closed:
        await ctx.socket.close()
    if ctx.server_task is not None:
        await ctx.server_task

    if ctx.snes_socket is not None and not ctx.snes_socket.closed:
        await ctx.snes_socket.close()

    while ctx.input_requests > 0:
        ctx.input_queue.put_nowait(None)
        ctx.input_requests -= 1

    await input_task
Exemplo n.º 13
0
#!/usr/bin/python
from Subs import *
from Patch import *
from types import TupleType

from Config import patch, subs

import re
import Patch
Patch.reload_data(0)

subusage = {}

# colors = 'ROGBVndcihs'
colors = 'ndcihs'

color_chart = {
    '1-01' : 'ROYd',   # broadway (morning - afternoon)
    '1-02' : 'i',      # int. mission
    '1-03' : 'R',      # phone booth
    '1-04' : 'RBVh',   # hotbox
    '1-05' : 'RBd',    # off broadway
    '1-06' : 'ROYd',   # ext. mission
    '1-07' : 'ROYn',   # gambler intro, off broadway
    '1-08' : 'ROBIVc',  # havana, clubs
    '1-09' : 'ROYBIVc', # havana, outside, night
    '1-10' : 'BVn',     # ext. mission, night (4am)

    '2-01' : 'RBIVh',  # hotbox
    '2-02' : 'RBn',    # more can i wish you
    '2-03' : 'GBs',    # sewer (crap game)
Exemplo n.º 14
0
def get_adjuster_settings(romfile: str) -> typing.Tuple[str, bool]:
    if hasattr(get_adjuster_settings, "adjuster_settings"):
        adjuster_settings = getattr(get_adjuster_settings, "adjuster_settings")
    else:
        adjuster_settings = persistent_load().get("adjuster", {}).get(
            "last_settings_3", {})

    if adjuster_settings:
        import pprint
        import Patch
        adjuster_settings.rom = romfile
        adjuster_settings.baserom = Patch.get_base_rom_path()
        adjuster_settings.world = None
        whitelist = {
            "disablemusic", "fastmenu", "heartbeep", "heartcolor",
            "ow_palettes", "quickswap", "uw_palettes", "sprite"
        }
        printed_options = {
            name: value
            for name, value in vars(adjuster_settings).items()
            if name in whitelist
        }
        if hasattr(adjuster_settings, "sprite_pool"):
            sprite_pool = {}
            for sprite in getattr(adjuster_settings, "sprite_pool"):
                if sprite in sprite_pool:
                    sprite_pool[sprite] += 1
                else:
                    sprite_pool[sprite] = 1
            if sprite_pool:
                printed_options["sprite_pool"] = sprite_pool

        if hasattr(get_adjuster_settings, "adjust_wanted"):
            adjust_wanted = getattr(get_adjuster_settings, "adjust_wanted")
        elif persistent_load().get("adjuster", {}).get(
                "never_adjust", False):  # never adjust, per user request
            return romfile, False
        else:
            adjust_wanted = input(
                f"Last used adjuster settings were found. Would you like to apply these? \n"
                f"{pprint.pformat(printed_options)}\n"
                f"Enter yes, no or never: ")
        if adjust_wanted and adjust_wanted.startswith("y"):
            if hasattr(adjuster_settings, "sprite_pool"):
                from Adjuster import AdjusterWorld
                adjuster_settings.world = AdjusterWorld(
                    getattr(adjuster_settings, "sprite_pool"))

            adjusted = True
            import Adjuster
            _, romfile = Adjuster.adjust(adjuster_settings)

            if hasattr(adjuster_settings, "world"):
                delattr(adjuster_settings, "world")
        elif adjust_wanted and "never" in adjust_wanted:
            persistent_store("adjuster", "never_adjust", True)
            return romfile, False
        else:
            adjusted = False
            import logging
            if not hasattr(get_adjuster_settings, "adjust_wanted"):
                logging.info(f"Skipping post-patch adjustment")
        get_adjuster_settings.adjuster_settings = adjuster_settings
        get_adjuster_settings.adjust_wanted = adjust_wanted
        return romfile, adjusted
    return romfile, False
Exemplo n.º 15
0
    def _gen_rom(team: int, player: int):
        sprite_random_on_hit = type(
            args.sprite[player]) is str and args.sprite[player].lower(
            ) == 'randomonhit'
        use_enemizer = (world.boss_shuffle[player] != 'none'
                        or world.enemy_shuffle[player] != 'none'
                        or world.enemy_health[player] != 'default'
                        or world.enemy_damage[player] != 'default'
                        or args.shufflepots[player] or sprite_random_on_hit)

        rom = LocalRom(args.rom)

        patch_rom(world, rom, player, team, use_enemizer)

        if use_enemizer:
            patch_enemizer(world, player, rom, args.enemizercli,
                           sprite_random_on_hit)

        if args.race:
            patch_race_rom(rom)

        world.spoiler.hashes[(player, team)] = get_hash_string(rom.hash)

        apply_rom_settings(rom, args.heartbeep[player],
                           args.heartcolor[player], args.quickswap[player],
                           args.fastmenu[player], args.disablemusic[player],
                           args.sprite[player], args.ow_palettes[player],
                           args.uw_palettes[player])

        mcsb_name = ''
        if all([
                world.mapshuffle[player], world.compassshuffle[player],
                world.keyshuffle[player], world.bigkeyshuffle[player]
        ]):
            mcsb_name = '-keysanity'
        elif [
                world.mapshuffle[player], world.compassshuffle[player],
                world.keyshuffle[player], world.bigkeyshuffle[player]
        ].count(True) == 1:
            mcsb_name = '-mapshuffle' if world.mapshuffle[
                player] else '-compassshuffle' if world.compassshuffle[
                    player] else '-keyshuffle' if world.keyshuffle[
                        player] else '-bigkeyshuffle'
        elif any([
                world.mapshuffle[player], world.compassshuffle[player],
                world.keyshuffle[player], world.bigkeyshuffle[player]
        ]):
            mcsb_name = '-%s%s%s%sshuffle' % (
                'M' if world.mapshuffle[player] else '',
                'C' if world.compassshuffle[player] else '',
                'S' if world.keyshuffle[player] else '',
                'B' if world.bigkeyshuffle[player] else '')

        outfilepname = f'_T{team + 1}' if world.teams > 1 else ''
        if world.players > 1:
            outfilepname += f'_P{player}'
        if world.players > 1 or world.teams > 1:
            outfilepname += f"_{world.player_names[player][team].replace(' ', '_')}" if world.player_names[
                player][team] != 'Player%d' % player else ''
        outfilesuffix = (
            '_%s_%s-%s-%s-%s%s_%s-%s%s%s%s%s' %
            (world.logic[player], world.difficulty[player],
             world.difficulty_adjustments[player], world.mode[player],
             world.goal[player],
             "" if world.timer[player] in [False, 'display'] else "-" +
             world.timer[player], world.shuffle[player], world.algorithm,
             mcsb_name, "-retro" if world.retro[player] else "",
             "-prog_" + world.progressive[player] if world.progressive[player]
             in ['off', 'random'] else "", "-nohints" if
             not world.hints[player] else "")) if not args.outputname else ''
        rompath = output_path(
            f'{outfilebase}{outfilepname}{outfilesuffix}.sfc')
        rom.write_to_file(rompath)
        if args.create_diff:
            import Patch
            Patch.create_patch_file(rompath)
        return (player, team, list(rom.name))
Exemplo n.º 16
0
 def updatestagelevels(self):
     self.master.after(100, self.updatestagelevels)
     for lev, idx in zip(self.oldlevels, xrange(0, 68 + 1)):
         self.stage.updatelightlevel(Patch.get_channel_name(idx + 1), lev)
Exemplo n.º 17
0
    def _gen_rom(team: int, player: int):
        use_enemizer = (world.boss_shuffle[player] != 'none'
                        or world.enemy_shuffle[player]
                        or world.enemy_health[player] != 'default'
                        or world.enemy_damage[player] != 'default'
                        or world.shufflepots[player]
                        or world.bush_shuffle[player]
                        or world.killable_thieves[player])

        rom = LocalRom(args.rom)

        patch_rom(world, rom, player, team, use_enemizer)

        if use_enemizer:
            patch_enemizer(world, team, player, rom, args.enemizercli)

        if args.race:
            patch_race_rom(rom, world, player)

        world.spoiler.hashes[(player, team)] = get_hash_string(rom.hash)

        palettes_options = {}
        palettes_options['dungeon'] = args.uw_palettes[player]
        palettes_options['overworld'] = args.ow_palettes[player]
        palettes_options['hud'] = args.hud_palettes[player]
        palettes_options['sword'] = args.sword_palettes[player]
        palettes_options['shield'] = args.shield_palettes[player]
        palettes_options['link'] = args.link_palettes[player]

        apply_rom_settings(rom, args.heartbeep[player],
                           args.heartcolor[player], args.quickswap[player],
                           args.fastmenu[player], args.disablemusic[player],
                           args.sprite[player], palettes_options, world,
                           player, True)

        mcsb_name = ''
        if all([
                world.mapshuffle[player], world.compassshuffle[player],
                world.keyshuffle[player], world.bigkeyshuffle[player]
        ]):
            mcsb_name = '-keysanity'
        elif [
                world.mapshuffle[player], world.compassshuffle[player],
                world.keyshuffle[player], world.bigkeyshuffle[player]
        ].count(True) == 1:
            mcsb_name = '-mapshuffle' if world.mapshuffle[player] else \
                '-compassshuffle' if world.compassshuffle[player] else \
                '-universal_keys' if world.keyshuffle[player] == "universal" else \
                '-keyshuffle' if world.keyshuffle[player] else '-bigkeyshuffle'
        elif any([
                world.mapshuffle[player], world.compassshuffle[player],
                world.keyshuffle[player], world.bigkeyshuffle[player]
        ]):
            mcsb_name = '-%s%s%s%sshuffle' % (
                'M' if world.mapshuffle[player] else '',
                'C' if world.compassshuffle[player] else '',
                'U' if world.keyshuffle[player] == "universal" else
                'S' if world.keyshuffle[player] else '',
                'B' if world.bigkeyshuffle[player] else '')

        outfilepname = f'_T{team + 1}' if world.teams > 1 else ''
        outfilepname += f'_P{player}'
        outfilepname += f"_{world.player_names[player][team].replace(' ', '_')}" \
            if world.player_names[player][team] != 'Player%d' % player else ''
        outfilestuffs = {
            "logic": world.logic[player],  # 0
            "difficulty": world.difficulty[player],  # 1
            "item_functionality": world.item_functionality[player],  # 2
            "mode": world.mode[player],  # 3
            "goal": world.goal[player],  # 4
            "timer": str(world.timer[player]),  # 5
            "shuffle": world.shuffle[player],  # 6
            "algorithm": world.algorithm,  # 7
            "mscb": mcsb_name,  # 8
            "retro": world.retro[player],  # 9
            "progressive": world.progressive,  # A
            "hints": 'True' if world.hints[player] else 'False'  # B
        }
        #                  0  1  2  3  4 5  6  7 8 9 A B
        outfilesuffix = (
            '_%s_%s-%s-%s-%s%s_%s-%s%s%s%s%s' % (
                #  0          1      2      3    4     5    6      7     8        9         A     B           C
                # _noglitches_normal-normal-open-ganon-ohko_simple-balanced-keysanity-retro-prog_random-nohints
                # _noglitches_normal-normal-open-ganon     _simple-balanced-keysanity-retro
                # _noglitches_normal-normal-open-ganon     _simple-balanced-keysanity      -prog_random
                # _noglitches_normal-normal-open-ganon     _simple-balanced-keysanity                  -nohints
                outfilestuffs["logic"],  # 0
                outfilestuffs["difficulty"],  # 1
                outfilestuffs["item_functionality"],  # 2
                outfilestuffs["mode"],  # 3
                outfilestuffs["goal"],  # 4
                "" if outfilestuffs["timer"] in ['False', 'none', 'display']
                else "-" + outfilestuffs["timer"],  # 5
                outfilestuffs["shuffle"],  # 6
                outfilestuffs["algorithm"],  # 7
                outfilestuffs["mscb"],  # 8
                "-retro" if outfilestuffs["retro"] == "True" else "",  # 9
                "-prog_" + outfilestuffs["progressive"] if
                outfilestuffs["progressive"] in ['off', 'random'] else "",  # A
                "-nohints" if not outfilestuffs["hints"] == "True" else ""
            )  # B
        ) if not args.outputname else ''
        rompath = output_path(
            f'{outfilebase}{outfilepname}{outfilesuffix}.sfc')
        rom.write_to_file(rompath, hide_enemizer=True)
        if args.create_diff:
            Patch.create_patch_file(rompath)
        return player, team, bytes(rom.name).decode()
Exemplo n.º 18
0
def extractMeasurements(t, depthMsg, boundingBoxMsg, odometryMsg, imageMsg):
    global f_odometry
    newMeasurements = []
    cylinderR = 1
    boundingBoxMinPixelSpace = 15
    currPos = [
        odometryMsg.pose.position.x, odometryMsg.pose.position.y,
        odometryMsg.pose.position.z
    ]
    traj3d.append(currPos)

    depthImage = bridge.imgmsg_to_cv2(depthMsg, desired_encoding="32FC1")
    # Rotate RGB image if necessary
    depthImage = cv2.rotate(depthImage, cv2.ROTATE_180)
    rgbImage = bridge.imgmsg_to_cv2(imageMsg, desired_encoding="bgr8")

    patches = []
    for b in boundingBoxMsg.bounding_boxes:
        # Check if desired object class
        if (b.Class != 'car' and b.Class != 'truck'):
            continue
        xmin = max(b.xmin, 0)
        ymin = max(b.ymin, 0)
        xmax = b.xmax
        ymax = b.ymax

        # Check if detection not at boundary
        if (xmin < boundingBoxMinPixelSpace or ymin < boundingBoxMinPixelSpace
                or xmax > imgWidth - 1 - boundingBoxMinPixelSpace
                or ymax > imgHeight - 1 - boundingBoxMinPixelSpace):
            continue

        p = Patch(depthImage[ymin:ymax + 1, xmin:xmax + 1], xmin, xmax, ymin,
                  ymax)

        # Only use detections with depth information inside circle
        if ~np.isnan(p.medianDepthCircle):
            patches.append(p)

    # Sort patches according to minimum depth values inside bounding boxes
    patches.sort(key=operator.attrgetter('minDepth'))

    qi = [
        odometryMsg.pose.orientation.w, odometryMsg.pose.orientation.x,
        odometryMsg.pose.orientation.y, odometryMsg.pose.orientation.z
    ]
    R_world_imu = quadToRot(qi)

    for p in patches:
        rgbImage = ImagePainter.markPatch(rgbImage, p)
        pxCoords = p.getFlippedCenterCoordinates()
        coord3d = Kinv.dot(pxCoords.T)
        coord3d = coord3d / np.linalg.norm(coord3d) * (
            p.medianDepthCircle + cylinderR
        )  # Measurement vector in cameara frame
        coord3d = R_imu_cam.dot(coord3d) - np.array(x_imu_cam)
        coord3d = R_world_imu.dot(coord3d) - np.array(x_world_imu) + np.array(
            currPos)
        coord3d = coord3d.tolist()
        #coord3d = (np.array(currPos)+(R_world_imu.dot(R_imu_cam.dot(coord3d)))-np.array(x_world_imu)).tolist()
        measurements3d.append(coord3d)
        newMeasurements.append(coord3d)
        f_measurements.writeMeasurement(t, coord3d)
    f_odometry.writeOdometry(t, odometryMsg)
    return rgbImage, patches, newMeasurements
Exemplo n.º 19
0
import sys, time, socket
sys.path.append("../light8")
import Tix as tk

import Patch, Timeline, dmxclient, xmlrpclib
import TheShow

Patch.reload_data()

class ShowRunner(tk.Frame):
    def __init__(self, master, show):
        tk.Frame.__init__(self, master)
        self.master = master

        self.show = show
        self.find_player()
        self.build_timeline_list()
    def build_timeline_list(self):
        self.tl_list = tk.Frame(self)
        for tl in self.show.get_timelines():
            b=tk.Button(self.tl_list,text=tl,
                        anchor='w',pady=1)
            b.config(command=lambda tl=tl: self.set_timeline(tl))
            b.pack(side='top',fill='x')
        self.tl_list.pack()
    def set_timeline(self, tlname):
        print "TimelineDMX: set timeline to", tlname
        self.show.set_timeline(tlname)
    def find_player(self):
        self.player = xmlrpclib.Server("http://spot:8040")
    def send_levels(self):
Exemplo n.º 20
0
 def get_data(self,*args):
     Subs.reload_data(self.DUMMY)
     Patch.reload_data(self.DUMMY)
     print "Light 8.8:", len(Patch.patch), "dimmers patched"
     print "Light 8.8:", len(Subs.subs), "submasters loaded"