Esempio n. 1
0
def set_figure_geometry(index):

    window, n = plt.get_current_fig_manager().window, index+1
######################################################################
    xmax, ymax, dx, dy=5120, 1440, 840, 670
    window.setGeometry(xmax-n*dx,ymax-dy,dx,dy)
    return
######################################################################

    try:
        # attempt to fetch size of monitor
        from screeninfo import get_monitors
        xmax, ymax=get_monitors()[0].width, get_monitors()[0].height
    except:
        warnings.warn('could not find screeninfo module; run % pip install screeninfo')
        return      # failed to fetch current monitor size

    # attempt to fetch size of current window
    if callable(getattr(window,'winfo_width',None)):    # Tkagg
        dx,dy=window.winfo_width(),window.winfo_height()
        window.wm_geometry('+{}+{}'.format(xmax-n*dx,ymax-dy))
    elif callable(getattr(window,'width',None)):        # qt{4,5}agg
        dx,dy=window.width(), window.height()
        window.setGeometry(xmax-n*dx,ymax-dy,dx,dy)
    elif getattr(window,'Size',None):                   # works for wxagg
        dx,dy=window.Size
        window.Move(xmax-n*dx, ymax-dy)
    else:
        warnings.warn('failed to auto-position matplotlib windows: unknown backend')
Esempio n. 2
0
def get_center_of_current_monitor():
    mouse = pymouse.PyMouse()
    mouse_x, mouse_y = mouse.position()

    # print("mouse.x: {0}, mouse.y: {1}".format(mouse_x, mouse_y))

    monitors = get_monitors()

    for iMonitor in range(0, len(monitors)):
        monitor = monitors[iMonitor]

        monitor_left = monitor.x
        monitor_right = monitor.x + monitor.width
        monitor_bottom = monitor.y
        monitor_top = monitor.y + monitor.height

        # print("monitor: {0}, width: {1}".format(iMonitor, monitor.width))
        # print("left: {0}, right: {1}".format(monitor_left, monitor_right))

        if monitor_left <= mouse_x < monitor_right and monitor_bottom <= monitor.y < monitor_top:
            x = int((monitor_left + monitor_right)/2)
            y = int((monitor.y + monitor.height)/2)
            return x, y, monitor.width, monitor.height

    return None, None, None, None
Esempio n. 3
0
def get_desktop_geometry():

    workspaces = screen.get_workspaces()

    desktop = Wnck.Screen.get_active_workspace(screen)
    #print('ActiveDesktop: ', desktop)
    window_list = screen.get_windows()

    #print(get_monitors())
    mon_LIST=[]
    for m in get_monitors():
        edge_left = re.findall('\+([^]]*)\+',str(m))
        #print('edge_left= ',edge_left)
        if int(edge_left[0]) == 0:
            screen_edge = 0
        else:
            screen_edge = edge_left[0]
        mon_LIST.append(int(screen_edge))

        #print('m= ',str(m))
        monitors = len(mon_LIST)
    #print ('Number of Monitors= ', str(monitors))
    #print('Right Monitor starts at ', str(screen_edge))
    mon_LIST.sort(key=int)
    #print('mon_LIST',mon_LIST)
    return int(monitors),mon_LIST
Esempio n. 4
0
    def __init__(self, height, width, pos):
        self.height = height
        self.width = width
        self.pos = pos                          # Trackbar positons dict
        self.preview_on = True                      # Falg: show preview window
        self.fullscreen = not cv2.WINDOW_FULLSCREEN # Flag: fullscreen (off)
        self._debugger_off = not self.DEBUGGER_MODE # Flag: debugger status
        self.output_img_height = self.height * 2
        self.cur_monitor_idx = 0                    # Default monitor
        self.monitors_lst = [self._add_canvas(m) for m in get_monitors()]

        def on_change(_):
            """Updates values in self.pos if any change."""
            self._get_trackbar_values()
        
        cv2.namedWindow(self.C_HDR, cv2.WINDOW_NORMAL)
        cv2.namedWindow(self.O_HDR, cv2.WINDOW_NORMAL)
        cv2.createTrackbar('mask centre', self.C_HDR, int(self.pos['m_cntr'] * 100),\
                           100, on_change)
        cv2.createTrackbar('mask bottom', self.C_HDR, int(self.pos['m_btm'] * 100),\
                           100, on_change)
        cv2.createTrackbar('mask side', self.C_HDR, int(self.pos['m_side'] * 100), 400, on_change)
        cv2.createTrackbar('mask offset', self.C_HDR, int(self.pos['m_y_offset'] * 1000),\
                           1000, on_change)
        cv2.createTrackbar('image x', self.C_HDR, int(self.width / 2), \
                           self.width, on_change)
        cv2.createTrackbar('image y', self.C_HDR, int(self.height / 2), \
                           self.height, on_change)
        cv2.createTrackbar('scale', self.C_HDR, int(self.pos['scale'] * 100), 300, on_change)
        cv2.createTrackbar('loop video', self.C_HDR, self.pos['loop_video'], 1, on_change)
        cv2.createTrackbar('Track Faces', self.C_HDR, self.pos['tracking_on'], 1, on_change)
        cv2.createTrackbar('  GrabCut iters', self.C_HDR, self.pos['gc_iters'], 5, on_change)
        cv2.createTrackbar('contrast', self.C_HDR, int(self.pos['contrast'] * 10), 30, on_change)
        cv2.createTrackbar('brightness', self.C_HDR, self.pos['brightness'], 100, on_change)
        self._get_trackbar_values()
Esempio n. 5
0
def get_resolution():
    try:
        from screeninfo import get_monitors
        m = get_monitors()
        return round_down_to(m[0].height, 500)
    except Exception as exc:
        log_warning('Could not get resolution! Using default ...\n\t{e}'.format(e=exc))
        return 1000
Esempio n. 6
0
    def validate_inputs(rows, cols, monitor_start):
        """
        This function validates the arguments to __init__().  It also
        returns a sorted 'monitors' list containing monitor details.
        """
        # Get the monitor information from screeninfo.get_monitors().
        monitors = get_monitors()
        # It's necessary to sort the result so that the far left monitor is
        # positioned first.
        monitors = sorted(monitors, key=lambda monitor: monitor.x)

        # 'rows', 'cols' must be real, positive numbers.
        if isinstance(rows, int) or isinstance(rows, float):
            if rows < 1:
                raise ValueError('rows arg must be greater than unity')
        else:
            raise ValueError('rows arg must be a numeric')
        if isinstance(cols, int) or isinstance(cols, float):
            if cols < 1:
                raise ValueError('cols arg must be greater than unity')
        else:
            raise ValueError('cols arg must be a numeric')

        # 'monitor_start' must be a single integer or a list of integers.
        error_string = (
            'monitor_start arg must be an integer or list of integers'
        )
        if isinstance(monitor_start, int):
            if monitor_start > len(monitors) - 1:
                error_string = (
                    'only %d monitors detected but monitor_start says to '
                    'start on monitor %d' % (len(monitors), monitor_start + 1)
                )
                raise ValueError(error_string)
        elif isinstance(monitor_start, list) or \
                isinstance(monitor_start, tuple):
            if len(monitor_start) == 0:
                raise ValueError(error_string)
            for value in monitor_start:
                if not isinstance(value, int):
                    raise ValueError(error_string)
                elif value > len(monitors) - 1:
                    error_string = (
                        'only %d monitors detected but monitor_start contains '
                        'monitor %d' % (len(monitors), value + 1)
                    )
                    raise ValueError(error_string)
        else:
            raise ValueError(error_string)

        # Rearrange or reduce the 'monitors' list depending on the value of
        # 'monitor_start'.
        if isinstance(monitor_start, int):
            monitors = monitors[monitor_start: ] + monitors[0: monitor_start]
        else:
            monitors = [monitors[i] for i in monitor_start]

        return monitors
Esempio n. 7
0
 def get_monitors_or_default(tkroot=None):
     result = None
     if PlatformUtility.platform_is_mac() and tkroot is None:
         result = [Monitor(0, 0, 1920, 1080)]
     elif PlatformUtility.platform_is_mac() and tkroot is not None:
         result = [Monitor(0, 0, tkroot.winfo_screenwidth(), tkroot.winfo_screenheight())]
     else:
         result = get_monitors()
     return result
def initStream(frame, opts) :
    frame_h, frame_w = _frame.shape[:2]
    print("Captured image size (height x width) = {}x{}".format(frame_h, frame_w))

    if opts.video_stream :
        monitors = get_monitors()
        if len(monitors) == 0 :
            print("No monitor connected, videostream won't be resized")
        else :
            cv2.namedWindow(VIDEO_WINDOW, cv2.WINDOW_NORMAL)
            mon_h = monitors[0].height
            mon_w = monitors[0].width
            ratio = frame_h/frame_w
            if mon_w*ratio > mon_h :
                cv2.resizeWindow(VIDEO_WINDOW, math.floor(mon_h/ratio), mon_h)
            else :
                cv2.resizeWindow(VIDEO_WINDOW, mon_w, math.floor(ratio*mon_w))
Esempio n. 9
0
    def get_config_window_bounds(self):
        """Reads bounds from config and, if monitor is specified, modify the values to match with the specified monitor

        :return: coords X and Y where set the browser window.
        """
        bounds_x = int(self.config.get_optional('Driver', 'bounds_x') or 0)
        bounds_y = int(self.config.get_optional('Driver', 'bounds_y') or 0)

        monitor_index = int(self.config.get_optional('Driver', 'monitor') or -1)
        if monitor_index > -1:
            try:
                monitor = screeninfo.get_monitors()[monitor_index]
                bounds_x += monitor.x
                bounds_y += monitor.y
            except NotImplementedError:
                self.logger.warn('Current environment doesn\'t support get_monitors')

        return bounds_x, bounds_y
Esempio n. 10
0
def get_screen_resolution():
    """
    Uses screeninfo or alternatively Tkinter to determine screen
    resolution as reported by OS. On some Linux window managers the
    result of Tkinter is that of all monitors combined. On Windows,
    Tkinter reports the primary monitor resolution.
    Screeninfo returns a list of monitors of which the resolution of
    the primary monitor is extracted.
    :return: tuple, (width, height), such as (1920, 1080)
    """
    try:  # Not supported on Travis-CI
        monitors = get_monitors()
        primary = monitors[0]
        w, h = primary.width, primary.height
        return w, h
    except (NotImplementedError, ValueError) as e:
        print("[Utilities] Screen resolution error:", repr(e))
        window = tk.Tk()
        width, height = window.winfo_screenwidth(), window.winfo_screenheight()
        window.destroy()
        return width, height
def graph(gui, daysList, nightsList, masterBlock, plotVertices = True, showDragWarn = False):
	bulkvertices = []
	vertX        = []
	vertY        = []
	masterX      = []
	masterY      = []
	airX         = []
	airY         = []
	monResList   = []
	
	#Clears previous graphs from memory
	reset_output()
	
	if plotVertices:
		#Add daytime period delimiting lines if appropriate
		if gui.restrictSearchBV.get() is True:
			for day in daysList:
				if len(day.vertices) > 0:
					#Add vertex at 0 to mark begining of day
					bulkvertices.append(coreC.vert(day.vertices[0].index, np.nan, day.vertices[0].vertType))
					#Get all vertices from bouts
					bulkvertices += day.vertices
					#Add vertex at 0 to mark end of day
					bulkvertices.append(coreC.vert(day.vertices[-1].index, np.nan, day.vertices[-1].vertType))
		#Else compile vertices for entire input file
		else:
			bulkvertices = masterBlock.vertices
			
		#Compile index number and temperature of all vertices
		for vertex in bulkvertices:
			vertX.append(gui.masterList[vertex.index][gui.dataPointCol])
			vertY.append(vertex.temp)
			
		#Output to HTML file
		output_file(gui.graphName)
	else:
		output_file(os.path.join(gui.coreDir, "misc_files", "tempGraph.html"))
	
	#Create column data source for vertex data so it can be manipulated in the interactive plot
	boutsSourceData = ColumnDataSource(data = dict(x = vertX, y = vertY))
	
	#Compile index number and temperature for every line in input file
	for line in gui.masterList:
		masterX.append(int(line[gui.dataPointCol]))
		masterY.append(float(line[gui.tempsCol]))
		
		#Compile air temperature if a valid column is present
		if gui.airValid is True:
			airX.append(int(line[gui.dataPointCol]))
			airY.append(float(line[gui.airTempCol]))
		
	
	#Set plot dimensions
	if gui.plotDimVar.get() is 1:
		#Get monitor resolution if "auto" selected
		for monitor in get_monitors():
			monResList.append(str(monitor))	
		
		#Extract monitor width and height
		resRE = re.search("(\d+)x(\d+)", monResList[0])
		monX = int(resRE.group(1))
		monY = int(resRE.group(2))
		plotX = (monX - 200)
		plotY = (monY - 200)
	#Get user dimension values if "manual" selected
	else:
		plotX = int(gui.plotDimXE.get())
		plotY = int(gui.plotDimYE.get())
	
	#Initialize hover tool (provides information about individual datapoints)
	hover = HoverTool(tooltips=[("Data Point", "$x{int}"), ("Temperature", "$y")])

	#(flag) may not be neccessary
	# for y in masterY:
		# float(y)
	
	#Get name of plot
	if plotVertices:
		plotName = gui.graphName[:-5]
	else:
		#Get input file root name
		tempRE = re.search((".*\."), os.path.basename(os.path.normpath(gui.inputFileAdvE.get())))
		#Assign default plot name
		if tempRE:
			plotName = tempRE.group(0)[:-1]
		else:
			plotName = os.path.basename(os.path.normpath(gui.inputFileAdvE.get()))

	#Detect best y axis range
	if gui.airValid is True:
		yMin = (float(min(min(masterY), min(airY))) - 2)
		yMax = (float(max(max(masterY), max(airY))) + 2)
	else:
		yMin = (float(min(masterY)) - 2)
		yMax = (float(max(masterY)) + 2)
		
	#Create core plot
	plot  = figure(tools = [hover, "box_zoom, wheel_zoom, pan, reset, save"],
				   x_range = [int(masterX[0]), int(masterX[len(masterX) - 1])],
				   y_range = [yMin, yMax],
				   # y_range = [float(min((float(min(airY)), float(min(masterY)))) - 2), (max(max(airY), max(masterY)) + 2)], 
				   title = plotName,
				   x_axis_label= "Data Point", y_axis_label = "Temperature (C)", plot_width = plotX, plot_height = plotY)
				   
	
	#Add vertical lines delimiting days
	if gui.showDayDelimsBV.get() is True:
		for day in daysList:
			vline = Span(location = int(gui.masterList[day.start][gui.dataPointCol]), dimension = "height",
				    line_color = gui.dayMarkerColorVar.get(), line_width = float(gui.dayMarkerSize_E.get()), line_alpha = 0.6)
			plot.renderers.extend([vline])
	
	#Get size settings from GUI
	plot.title.text_font_size = (gui.titleFontSizeE.get() + "pt")
	plot.axis.axis_label_text_font_size  = (gui.axisTitleFontSizeE.get() + "pt")
	plot.axis.major_label_text_font_size  = (gui.axisLabelFontSizeE.get() + "pt")	
	plot.axis.major_tick_line_width = int(gui.axisTickSizeE.get())
	plot.axis.minor_tick_line_width = int(gui.axisTickSizeE.get())
	plot.axis.major_tick_out = int(gui.axisTickSizeE.get())
	plot.axis.minor_tick_out = int(gui.axisTickSizeE.get())

	#Append vertex x and y values to data dictionary
	data = {"x": [], "y": []}
	for x in vertX: data["x"].append(x)
	for y in vertY: data["y"].append(y)
	
	#Generate table with vertex information
	src = ColumnDataSource(data)
	columns = [
				TableColumn(field = "x", title = "Data Point"),
				TableColumn(field = "y", title = "Temperature")
			  ]
	data_table = DataTable(source = src, columns = columns, width = 500, height = 20000)
	
	if gui.editModeBV.get():
		#Show drag warning if applicable
		if showDragWarn:
			dragWarn(gui)
			
		#Plot air temperatures
		if gui.showAirTempBV.get() is True and gui.airValid:
			# plot.circle(airX, airY, size = 5, color = "black", alpha = 1, legend = "Air Temeprature")
			plot.line(airX, airY, line_width = float(gui.airTempSize_E.get()), color = gui.airTempColorVar.get(), line_alpha = 1, legend = "Air Temeprature")
		
		#Plot egg temperatures
		plot.circle(masterX, masterY, size = float(gui.eggTempPointSize_E.get()), color = gui.eggTempPointColorVar.get(), legend = "Egg Temperature")
		plot.line(masterX, masterY, line_width = float(gui.eggTempLineSize_E.get()), color = gui.eggTempLineColorVar.get())

		#Plot verticies as large circles if edit mode selected
		renderer = plot.circle  (
									"x",
									"y",
									size = (float(gui.boutSize_E.get()) * 3),
									color = "black",
									fill_color = gui.boutColorVar.get(),
									fill_alpha = 0.8,
									legend = "Prediced Incubation Shift",
									source = src
								)
		
		draw_tool = PointDrawTool(renderers = [renderer], empty_value = 1)
		plot.add_tools(draw_tool)
		plot.toolbar.active_drag = draw_tool
		
		
			
	#Else plot verticies as lines
	else:		
		#Plot air temperatures
		if gui.showAirTempBV.get() is True and gui.airValid:
			# plot.circle(airX, airY, size = 5, color = "black", alpha = 1, legend = "Air Temeprature")
			plot.line(airX, airY, line_width = float(gui.airTempSize_E.get()), color = gui.airTempColorVar.get(), line_alpha = 1, legend = "Air Temeprature")
			
		#Plot egg temperatures
		plot.circle(masterX, masterY, size = float(gui.eggTempPointSize_E.get()), color = gui.eggTempPointColorVar.get(), legend = "Egg Temperature")	
		plot.line(masterX, masterY, line_width = float(gui.eggTempLineSize_E.get()), color = gui.eggTempLineColorVar.get())
			
		#Add vertices
		plot.line("x", "y", line_width = float(gui.boutSize_E.get()), legend = "Detected Bout", line_color = gui.boutColorVar.get(), source = boutsSourceData)
	
	if gui.showGridBV.get() is False:
		plot.grid.visible = False
	
	plot.legend.label_text_font_size = (gui.legendFontSizeE.get() + "pt")
	plot.background_fill_color = None
	plot.border_fill_color = None
	# plot.outline_color = None
			
	#Generate plot
	show(column(plot, widgetbox(data_table)))
Esempio n. 12
0
def get_configuration(args):
    custom_defaults = get_custom_defaults()

    write_file = any([args.write_file, args.open, args.finder])
    if args.transparent:
        file_ext = ".mov"
    elif args.gif:
        file_ext = ".gif"
    else:
        file_ext = ".mp4"

    file_writer_config = {
        "write_to_movie":
        not args.skip_animations and write_file,
        "break_into_partial_movies":
        custom_defaults["break_into_partial_movies"],
        "save_last_frame":
        args.skip_animations and write_file,
        "save_pngs":
        args.save_pngs,
        # If -t is passed in (for transparent), this will be RGBA
        "png_mode":
        "RGBA" if args.transparent else "RGB",
        "movie_file_extension":
        file_ext,
        "mirror_module_path":
        custom_defaults["directories"]["mirror_module_path"],
        "output_directory":
        args.video_dir or custom_defaults["directories"]["output"],
        "file_name":
        args.file_name,
        "input_file_path":
        args.file or "",
        "open_file_upon_completion":
        args.open,
        "show_file_location_upon_completion":
        args.finder,
        "quiet":
        args.quiet,
    }

    module = get_module(args.file)
    config = {
        "module": module,
        "scene_names": args.scene_names,
        "file_writer_config": file_writer_config,
        "quiet": args.quiet or args.write_all,
        "write_all": args.write_all,
        "start_at_animation_number": args.start_at_animation_number,
        "preview": not write_file,
        "end_at_animation_number": None,
        "leave_progress_bars": args.leave_progress_bars,
    }

    # Camera configuration
    config["camera_config"] = get_camera_configuration(args, custom_defaults)

    # Default to putting window in the upper right of screen,
    # but make it full screen if -f is passed in
    monitor = get_monitors()[0]
    window_width = monitor.width
    if not args.full_screen:
        window_width //= 2
    window_height = window_width * 9 // 16
    config["window_config"] = {
        "size": (window_width, window_height),
    }

    # Arguments related to skipping
    stan = config["start_at_animation_number"]
    if stan is not None:
        if "," in stan:
            start, end = stan.split(",")
            config["start_at_animation_number"] = int(start)
            config["end_at_animation_number"] = int(end)
        else:
            config["start_at_animation_number"] = int(stan)

    config["skip_animations"] = any([
        args.skip_animations,
        args.start_at_animation_number,
    ])
    return config
Esempio n. 13
0
import keyboard
import math
from screeninfo import get_monitors
import datetime


def handle_focus(event):
    if event.widget == root:
        root.focus_set()
        calcInput.userInputEntry.focus_set()


global screenWidth, screenHeight

root = tkinter.Tk()
screenInfo = get_monitors()[0]
screenWidth = screenInfo.width
screenHeight = screenInfo.height
print(screenWidth, screenHeight)

root.title("Calculator")
root.geometry("%sx67+%s+%s" % (screenWidth, screenWidth, screenHeight - 40))
root.resizable(False, False)
root.wm_attributes('-type', 'splash')
root.attributes("-topmost", True)
global histFilename
histFilename = 'calculatorHistory.txt'


class CalculatorMain:
    def __init__(self, main):
def main(IP, my_username, color_input):
    # Reading settings
    settings = Settings_Reader.Read_Settings_Client()
    fps = settings['Client_Update_Fps']
    background_color = settings['Background_Color']
    Draw_grid_bool = settings['Draw_Grid']
    # Calculating brightness
    brightness = math.sqrt(0.241 * background_color[0] * background_color[0] +
                           0.691 * background_color[1] * background_color[1] +
                           0.068 * background_color[2] * background_color[2])
    print(brightness)
    # checking if we have to invert the colors
    if brightness < 127:
        Negative_color = True
        print('must negative color')
    else:
        Negative_color = False
    # initilisating mixer and loading music and sfx

    pygame.mixer.pre_init(22100, -16, 1, 64)
    pygame.mixer.init()
    Sounds_dict = {
        'join_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'Join_sound.wav')),
        'quit_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'Quit_sound.wav')),
        'kill_sound':
        pygame.mixer.Sound(
            os.path.join('Sounds', 'Kill Confirmed  Sound Effect.wav')),
        'killed_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'Killed_sound.wav')),
        'click_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'click.wav')),
        'hover_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'hover.wav')),
        'countdown_3':
        pygame.mixer.Sound(os.path.join('Sounds', 'fight321.wav')),
        'Win_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'YouWin.wav')),
        'Lose_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'YouLose.wav')),
        'eating_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'eating_sound.wav')),
        'Destroyed_sound':
        pygame.mixer.Sound(os.path.join('Sounds', 'Destroyed.wav'))
    }
    # Sounds_dict['countdown_5']=pygame.mixer.Sound(os.path.join('Sounds','SFX Select.wav'))
    # Sounds_dict['countdown_4']=pygame.mixer.Sound(os.path.join('Sounds','SFX Select.wav'))
    # Sounds_dict['countdown_2']=pygame.mixer.Sound(os.path.join('Sounds','SFX Select.wav'))
    # Sounds_dict['countdown_1']=pygame.mixer.Sound(os.path.join('Sounds','SFX Select.wav'))
    # Sounds_dict['fight_sound']=pygame.mixer.Sound(os.path.join('Sounds','SFX Select.wav'))
    # ability to play movies was removed
    # Sounds_dict['Destroyed_video']= pygame.movie.Movie(os.path.join('Sounds','you-died-hd.mpg'))
    music = pygame.mixer.music.load(os.path.join('Sounds', 'MusicMix.wav'))
    pygame.mixer.music.play(-1)
    # initilisating variables,buttons,list,etc...
    key_pressed = ['Right', 0, 0]
    ##    width=500
    ##    height=500
    Grid_factor = 4
    Grid_size = [int(16 * Grid_factor), int(9 * Grid_factor)]
    s_list = []
    Sounds_to_play_decoded_check = ''
    # Getting monitor size
    for m in get_monitors():
        print(str(m))
        print(m.width)
        print(m.height)
    print((m.width // Grid_size[0]) * Grid_size[0])
    print((m.height // Grid_size[1]) * Grid_size[1])

    width = ((m.width) // Grid_size[0]) * Grid_size[0]
    height = ((m.height) // Grid_size[1]) * Grid_size[1]
    # initilisasing fonts
    pygame.font.init()
    myfont = pygame.font.SysFont('Comic Sans MS', int(width / 54.64))
    Winning_font = pygame.font.Font("Kilogram-GvBO.otf", int(width / 27.32))
    Window_size = (width, height)

    ##    width = 500
    ##    rows = 20

    HEADER_LENGTH = 50
    # IP=str(input('Give IP address: '))
    # IP = "192.168.100.2"
    PORT = 1234
    # my_username = input("Username: "******"Color ex:  115;123;23 or write common color names: "))
    color_input = snake_colors.handle_input_color(color_input)
    my_username += '|' + color_input

    # Create a socket
    # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX
    # socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Connect to a given ip and port
    client_socket.connect((IP, PORT))

    # Set connection to non-blocking state, so .recv() call won;t block, just return some exception we'll handle
    client_socket.setblocking(False)

    # Prepare username and header and send them
    # We need to encode username to bytes, then count number of bytes and prepare header of fixed size, that we encode to bytes as well
    username = my_username.encode('utf-8')
    username_header = f"{len(username):<{HEADER_LENGTH}}".encode('utf-8')
    client_socket.send(username_header + username)
    clock = pygame.time.Clock()
    Rectangle_lengh = Window_size[0] // Grid_size[0]

    #################START WINDOW
    Window = pygame.display.set_mode(Window_size,
                                     pygame.DOUBLEBUF | pygame.OPENGL)
    #Window.toggle_fullscreen()
    # pygame.FULLSCREEN |
    snakes = []
    snacks = []
    Rectangle_height = Window_size[1] // Grid_size[1]
    Game_started = False
    additional_info = ''
    timer = 0
    infinite_loop = True
    win_sound_played = False
    lose_sound_played = False
    cntrl_pressed = False

    while infinite_loop:
        glLoadIdentity()
        gluPerspective(45, (width / height), 0.1, 5000.0)

        #glTranslatef(0.0, 0.0, -55)
        #glTranslatef(0.0, 0.0, -55)
        #gluLookAt(0, 0, 55, 0, 0, 0, 0, 0.1, 1)
        pygame.time.delay(int(1000 / fps))
        ##    clock.tick(10)
        Mouse_pos = pygame.mouse.get_pos()

        if len(additional_info) == 1:
            additional_info = 'Game starting in ' + additional_info
        elif additional_info == 'not started':
            additional_info = 'Wating for host to start the game'
        elif additional_info == 'Game_started':
            additional_info = 'Started'

            # buttons['start_game'].text=additional_info
        opengl_3d_draw.draw(snacks, snakes, Rectangle_height, Rectangle_lengh,
                            additional_info, Window_size, Grid_size,
                            background_color, Negative_color, Window,
                            Draw_grid_bool, Winning_font, myfont, Username,
                            key_pressed, cntrl_pressed)
        # Processing snake inputs
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    delete_all_snakes = True
                    infinite_loop = False
                if event.key == pygame.K_CAPSLOCK and cntrl_pressed == False:
                    cntrl_pressed = True
                elif event.key == pygame.K_CAPSLOCK:
                    cntrl_pressed = False
                if event.key == pygame.K_LEFT and key_pressed[0] == 'Up':
                    key_pressed[0] = 'Left'
                elif event.key == pygame.K_LEFT and key_pressed[0] == 'Down':
                    key_pressed[0] = 'Right'
                elif event.key == pygame.K_LEFT and key_pressed[0] == 'Left':
                    key_pressed[0] = 'Down'
                elif event.key == pygame.K_LEFT and key_pressed[0] == 'Right':
                    key_pressed[0] = 'Up'

                if event.key == pygame.K_RIGHT and key_pressed[0] == 'Up':
                    key_pressed[0] = 'Right'
                elif event.key == pygame.K_RIGHT and key_pressed[0] == 'Down':
                    key_pressed[0] = 'Left'
                elif event.key == pygame.K_RIGHT and key_pressed[0] == 'Left':
                    key_pressed[0] = 'Up'
                elif event.key == pygame.K_RIGHT and key_pressed[0] == 'Right':
                    key_pressed[0] = 'Down'

                #elif event.key == pygame.K_UP and key_pressed[0]!='Down':
                #    key_pressed[0] = 'Up'
                #elif event.key == pygame.K_DOWN and key_pressed[0]!='Up':
                #    key_pressed[0] = 'Down'
                # if event.key == pygame.K_a:
                #     key_pressed[1]='Left'

                # elif event.key == pygame.K_d:
                #     key_pressed[1]='Right'

                # elif event.key == pygame.K_w:
                #     key_pressed[1]='Up'

                # elif event.key == pygame.K_s:
                #     key_pressed[1]='Down'
                # else:
                #     key_pressed[1]=None
                # if event.key == pygame.K_f:
                #     key_pressed[2]='Left'

                # elif event.key == pygame.K_h:
                #     key_pressed[2]='Right'

                # elif event.key == pygame.K_t:
                #     key_pressed[2]='Up'

                # elif event.key == pygame.K_g:
                #     key_pressed[2]='Down'
                # else:
                #     key_pressed[2]=None
        # resseting varables
        if len(additional_info) == 1:
            if additional_info != '0':
                win_sound_played = False
                lose_sound_played = False
        # Sending inputs in a message
        message = str(
            key_pressed[0])  # +' '+str(key_pressed[1])+' '+str(key_pressed[2])

        # If message is not empty - send it
        if message:
            # Encode message to bytes, prepare header and convert to bytes, like for username above, then send
            message = message.encode('utf-8')
            message_header = f"{len(message):<{HEADER_LENGTH}}".encode('utf-8')
            client_socket.send(message_header + message)

        try:
            # Now we want to loop over received messages (there might be more than one) and print them
            while True:
                message_from_server = False
                # Receive our "header" containing username length, it's size is defined and constant
                username_header = client_socket.recv(HEADER_LENGTH)

                # If we received no data, server gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR)
                if not len(username_header):
                    print('Connection closed by the server')
                    sys.exit()

                # Convert header to int value
                username_length = int(username_header.decode('utf-8').strip())

                # Receive and decode username
                username = client_socket.recv(username_length).decode('utf-8')

                # Now do the same for message (as we received username, we received whole message, there's no need to check if it has any length)
                message_header = client_socket.recv(HEADER_LENGTH)
                message_length = int(message_header.decode('utf-8').strip())
                message = client_socket.recv(message_length).decode('utf-8')
                # Checking if the message comes from the server
                if username == 'SERVER(sending(Cube.info))':
                    # print('message: ',message)
                    message_from_server = True
                    # Decode the message
                    snakes, snacks, additional_info, Sounds_to_play_decoded = decoder.decode(
                        message)
                    # Play the sounds
                    if my_username.split('|')[
                            0] in additional_info and not win_sound_played:
                        print('you win')
                        Sounds_dict['Win_sound'].play()
                        win_sound_played = True
                    elif 'winner' in additional_info and my_username.split('|')[0] not in additional_info \
                            and not lose_sound_played:
                        print('You lose')
                        Sounds_dict['Lose_sound'].play()
                        lose_sound_played = True
                    if Sounds_to_play_decoded != Sounds_to_play_decoded_check:

                        # print('sound_change')
                        if Sounds_to_play_decoded != ['']:
                            for sound in Sounds_to_play_decoded:
                                # if sound[1]=='countdown_3'and not pygame.mixer.get_busy():
                                #     print('playing')
                                #     Sounds_dict['countdown_3'].play()

                                if sound[
                                        0] == my_username:  # not pygame.mixer.get_busy():
                                    # print(sound)
                                    # if sound=='join_sound':
                                    #     Sounds_dict['join_sound'].play()
                                    # except Exception as e:
                                    #     print (e)
                                    # print(sound[1])
                                    # print(Sounds_dict)
                                    # print(Sounds_dict['killed_sound'])
                                    # print(Sounds_dict[str(sound)])
                                    # if sound[1]=='join_sound':
                                    #     Sounds_dict['Destroyed_video'].play()
                                    Sounds_dict[sound[1]].set_volume(1)
                                    Sounds_dict[sound[1]].play()
                                    if sound[1] == 'Lose_sound':
                                        Sounds_dict['Destroyed_sound'].play()
                                elif ('countdown' in sound[1]
                                      or sound[1] == 'join_sound'
                                      or sound[1] == 'quit_sound'
                                      ) and not pygame.mixer.get_busy():
                                    Sounds_dict[sound[1]].play()
                                elif sound[0] != my_username and sound[
                                        0] != 'all':
                                    Sounds_dict[sound[1]].set_volume(0.3)
                                    if sound[1] == 'Lose_sound':
                                        Sounds_dict['Destroyed_sound'].play()
                                    else:

                                        # print('reducing volume')
                                        Sounds_dict[sound[1]].play()

                        Sounds_to_play_decoded_check = Sounds_to_play_decoded
                    # print(snakes)

                # Print message
                # print(f'{username} > {message}')

        except IOError as e:
            # This is normal on non blocking connections - when there are no incoming data error is going to be raised
            # Some operating systems will indicate that using AGAIN, and some using WOULDBLOCK error code
            # We are going to check for both - if one of them - that's expected, means no incoming data, continue as normal
            # If we got different error code - something happened
            if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
                print('Reading error: {}'.format(str(e)))
                # sys.exit()

            # We just did not receive anything
            continue

        except Exception as e:
            # Any other exception - something happened, exit
            print('Reading error: '.format(str(e)))
            # sys.exit()
            pass
        except:
            pass
Esempio n. 15
0
# Importing libraries __________________________________________________________________________________________________
from screeninfo import get_monitors
# ______________________________________________________________________________________________________________________

# Working out the value of u____________________________________________________________________________________________

# Finding out the resolution of the primary monitor_____________________________________________________________________

screen_resolution = None
for monitor in get_monitors():
    monitor = str(monitor)
    monitor_details = list(monitor[8:len(monitor) - 1])

    counter = 0
    for i in monitor_details:
        if i is "+":
            break
        counter += 1

    monitor_details = ''.join(monitor_details)

    if monitor_details[len(monitor_details) - 4:] == "+0+0":
        screen_resolution = monitor_details[:len(monitor_details) - 4]

screen_resolution = list(screen_resolution)

counter = 0
for i in screen_resolution:
    if i == "x":
        break
    counter += 1
Esempio n. 16
0
    def __init__(self, root):
        if sys.platform == "win32":
            app_x, app_y, app_width, app_height = 0, 0, 1200, 610
        else:
            app_x, app_y, app_width, app_height = 0, 0, 1200, 620

        for m in screeninfo.get_monitors():
            if m.x == 0 and m.y == 0:
                app_x = (m.width - app_width) // 2
                app_y = (m.height - app_height) // 2
                break
        geometry = "{}x{}+{}+{}".format(app_width, app_height, app_x, app_y)

        self.__root = root
        self.__root.resizable(0, 0)
        self.__root.geometry(geometry)
        self.__root.title("J1939 Monitor")
        self.__root.option_add("*Font", "맑은고딕 10")

        try:
            # sys.MEIPASS is temp directory for pyinstaller
            icon_path = os.path.join(getattr(sys, '_MEIPASS'), "j1939.png")
        except:
            icon_path = os.path.join(os.path.abspath("."), "j1939.png")
        self.__root.iconphoto(True, tkinter.PhotoImage(file=icon_path))

        self.__can_list = [tkinter.StringVar() for _ in range(6)]
        self.__para_list = [None for _ in range(6)]

        self.__uart = None
        self.__queue = queue.Queue()
        self.__con_string = tkinter.StringVar(value="Connect")
        self.__ucount = 0

        self.__lbl_port = tkinter.Label(self.__root,
                                        text="Serial Port",
                                        anchor="e")
        self.__cmb_port = ttk.Combobox(self.__root, values=sp.comports())
        self.__btn_conn = tkinter.Button(self.__root,
                                         textvariable=self.__con_string,
                                         command=self.__cb_btn_conn)
        self.__seperat1 = ttk.Separator(self.__root, orient="horizontal")

        for i in range(30):
            if i < 20:
                self.__root.rowconfigure(i, pad=1)
                self.__root.rowconfigure(i, weight=1)
                self.__root.rowconfigure(i, minsize=30)

            self.__root.columnconfigure(i, pad=1)
            self.__root.columnconfigure(i, weight=1)
            self.__root.columnconfigure(i, minsize=40)

        self.__lbl_port.grid(row=0,
                             column=20,
                             columnspan=3,
                             sticky="news",
                             padx=1,
                             pady=3)
        self.__cmb_port.grid(row=0,
                             column=23,
                             columnspan=4,
                             sticky="news",
                             padx=1,
                             pady=3)
        self.__btn_conn.grid(row=0,
                             column=27,
                             columnspan=3,
                             sticky="news",
                             padx=1,
                             pady=3)
        self.__seperat1.grid(row=1, column=0, columnspan=30, sticky="ew")

        for i in range(6):
            self.__para_list[i] = j1939_data.Parameter(
                i,
                tkinter.LabelFrame(self.__root, text="Parameter {}".format(i)))
Esempio n. 17
0
import os
import sys

#Fix kivy bug by specifying relevant info.
if sys.platform.startswith('linux'):
    os.environ['KIVY_GL_BACKEND'] = 'sdl2'
    os.environ['DISPLAY'] = ':0'
    os.environ['KIVY_AUDIO'] = 'sdl2'

from screeninfo import get_monitors
from kivy.config import Config

#Size window to fullscreen. Must be done at start of script. 
#Built-in kivy fullscreen method is buggy, causes debian systems to crash.
screenDimensions = get_monitors()[0]
Config.set('graphics', 'width', screenDimensions.width)
Config.set('graphics', 'height', screenDimensions.height)


from kivymd.app import MDApp
from kivymd.uix.button import MDRectangleFlatButton
from kivymd.uix.datatables import MDDataTable
from kivymd.uix.list import MDList, OneLineListItem, OneLineIconListItem, IconLeftWidget, OneLineAvatarIconListItem
from kivymd.uix.dialog import MDDialog
from kivymd.uix.behaviors.toggle_behavior import MDToggleButton
from kivymd.uix.button import MDIconButton
from kivymd.uix.label import MDLabel
from kivymd.icon_definitions import md_icons
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.card import MDCard
Esempio n. 18
0
def get_configuration(args):
    global __config_file__

    # ensure __config_file__ always exists
    if args.config_file is not None:
        if not os.path.exists(args.config_file):
            log.error(f"Can't find {args.config_file}.")
            if sys.platform == 'win32':
                log.info(
                    f"Copying default configuration file to {args.config_file}..."
                )
                os.system(f"copy default_config.yml {args.config_file}")
            elif sys.platform in ["linux2", "darwin"]:
                log.info(
                    f"Copying default configuration file to {args.config_file}..."
                )
                os.system(f"cp default_config.yml {args.config_file}")
            else:
                log.info("Please create the configuration file manually.")
            log.info("Read configuration from default_config.yml.")
        else:
            __config_file__ = args.config_file

    global_defaults_file = os.path.join(get_manim_dir(), "manimlib",
                                        "default_config.yml")

    if not (os.path.exists(global_defaults_file)
            or os.path.exists(__config_file__)):
        log.info(
            "There is no configuration file detected. Switch to the config file initializer:"
        )
        init_customization()

    elif not os.path.exists(__config_file__):
        log.info(
            f"Using the default configuration file, which you can modify in `{global_defaults_file}`"
        )
        log.info(
            "If you want to create a local configuration file, you can create a file named"
            f" `{__config_file__}`, or run `manimgl --config`")

    custom_config = get_custom_config()
    check_temporary_storage(custom_config)

    write_file = any([args.write_file, args.open, args.finder])
    if args.transparent:
        file_ext = ".mov"
    elif args.gif:
        file_ext = ".gif"
    else:
        file_ext = ".mp4"

    file_writer_config = {
        "write_to_movie":
        not args.skip_animations and write_file,
        "break_into_partial_movies":
        custom_config["break_into_partial_movies"],
        "save_last_frame":
        args.skip_animations and write_file,
        "save_pngs":
        args.save_pngs,
        # If -t is passed in (for transparent), this will be RGBA
        "png_mode":
        "RGBA" if args.transparent else "RGB",
        "movie_file_extension":
        file_ext,
        "mirror_module_path":
        custom_config["directories"]["mirror_module_path"],
        "output_directory":
        args.video_dir or custom_config["directories"]["output"],
        "file_name":
        args.file_name,
        "input_file_path":
        args.file or "",
        "open_file_upon_completion":
        args.open,
        "show_file_location_upon_completion":
        args.finder,
        "quiet":
        args.quiet,
    }

    if args.embed is None:
        module = get_module(args.file)
    else:
        with insert_embed_line(args.file, int(args.embed)) as alt_file:
            module = get_module(alt_file)

    config = {
        "module": module,
        "scene_names": args.scene_names,
        "file_writer_config": file_writer_config,
        "quiet": args.quiet or args.write_all,
        "write_all": args.write_all,
        "skip_animations": args.skip_animations,
        "start_at_animation_number": args.start_at_animation_number,
        "end_at_animation_number": None,
        "preview": not write_file,
        "presenter_mode": args.presenter_mode,
        "leave_progress_bars": args.leave_progress_bars,
    }

    # Camera configuration
    config["camera_config"] = get_camera_configuration(args, custom_config)

    # Default to making window half the screen size
    # but make it full screen if -f is passed in
    monitors = get_monitors()
    mon_index = custom_config["window_monitor"]
    monitor = monitors[min(mon_index, len(monitors) - 1)]
    window_width = monitor.width
    if not (args.full_screen or custom_config["full_screen"]):
        window_width //= 2
    window_height = window_width * 9 // 16
    config["window_config"] = {
        "size": (window_width, window_height),
    }

    # Arguments related to skipping
    stan = config["start_at_animation_number"]
    if stan is not None:
        if "," in stan:
            start, end = stan.split(",")
            config["start_at_animation_number"] = int(start)
            config["end_at_animation_number"] = int(end)
        else:
            config["start_at_animation_number"] = int(stan)

    return config
Esempio n. 19
0
import arcade
from screeninfo import get_monitors

monitors = get_monitors()

try:
    SCREEN_WIDTH = monitors[0].width
    SCREEN_HEIGHT = monitors[0].height
except Exception as e:
    print("Monitor resolution not found.")
    exit(1)

SCREEN_TITLE = "SCORE"


class StartButton(arcade.TextButton):
    def __init__(self, center_x, center_y, text_size, action_function):
        super().__init__(center_x,
                         center_y,
                         360,
                         150,
                         "START",
                         font_size=text_size,
                         shadow_color=arcade.color.RED,
                         font_color=arcade.color.BLACK,
                         button_height=0,
                         face_color=arcade.color.RED)
        self.action_function = action_function

    def on_press(self):
        self.action_function()
Esempio n. 20
0
from screeninfo import get_monitors # Screen Information (screeninfo) is a package to fetch location and size of physical screens.
# Window packages 
from tkinter import Toplevel, Tk, Label # Graphical User Interface (GUI) package
from PIL import Image, ImageTk # Python Imaging Librarier (PIL) package
# Processing packages
import re # Regular Expression (re) is a package to check, if a string contains the specified search pattern.
import numpy as np # Scientific computing package (NumPy)
import os # used to create path to image folder

current_path = os.getcwd()
folder_path = os.path.join(current_path, "Grating_Images")
if not os.path.exists(folder_path):
    os.makedirs(folder_path)
### Monitor controlling 
# Finds the resolution of all monitors that are connected.
active_monitors = get_monitors() # "monitor(screenwidth x screenheight + startpixel x + startpixel y)"


# Separates all numbers from a string
monitor_values=re.findall('([0-9]+)', str(active_monitors))
print(monitor_values)

# Assign the separated digits of the string to a variable
begin_monitor_horizontal = monitor_values[0]
begin_monitor_vertical = monitor_values[1]
begin_slm_horizontal = monitor_values[7]
begin_slm_vertical = monitor_values[8]


# Reverse the monitor pixel order (because, the SLM monitor is located ón the left side of the main monitor)
begin_slm_horizontal = str(int(begin_monitor_horizontal) - int(begin_slm_horizontal))
Esempio n. 21
0
# ---------- CONSTANTS ----------
FULLSCREEN = False

# ---------- VARIABLES ----------
fonts = create_fonts([32, 16, 14, 8])
fps = 60
clock = pygame.time.Clock()

# ---------- INIT ----------
COF = 2
size = width, height = int(640 * COF), int(360 * COF)
screen = pygame.display.set_mode(size)
if __name__ == '__main__':
    if FULLSCREEN:
        size = width, height = get_monitors()[0].width, get_monitors(
        )[0].height
        COF = width / 640
        screen = pygame.display.set_mode(
            size, pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN)
    else:
        COF = 2
        size = width, height = int(640 * COF), int(360 * COF)
        screen = pygame.display.set_mode(size)

    pygame.display.set_caption('Inventory')
    main_running = True
    im = pygame.image.load('im.png')

    while main_running:
        # world_noise = PerlinNoiseFactory(2, octaves=4, unbias=False, seed=random.randint(1, 55))
def draw_scene(vcd):
    # Prepare objects
    scene = scl.Scene(
        vcd)  # scl.Scene has functions to project images, transforms, etc.
    drawer_front = draw.Image(scene, "CAM_FRONT")
    drawer_rear = draw.Image(scene, "CAM_REAR")
    drawer_left = draw.Image(scene, "CAM_LEFT")
    drawer_right = draw.Image(scene, "CAM_RIGHT")

    frameInfoDrawer = draw.FrameInfoDrawer(vcd)

    setupViewer = draw.SetupViewer(scene, "vehicle-iso8855")

    # Class colormap
    colorMap = {
        'Car': (0, 0, 255),
        'Van': (255, 0, 0),
        'Truck': (127, 127, 0),
        'Pedestrian': (0, 255, 0),
        'Person_sitting': (0, 127, 127),
        'Tram': (127, 0, 127),
        'Misc': (127, 127, 127),
        'DontCare': (255, 255, 255),
        'Cyclist': (0, 127, 255),
        'Ego-car': (0, 0, 0),
        'Wall': (0, 0, 255),
        'Ground': (0, 255, 0)
    }

    # Get the size of the screen
    screen = screeninfo.get_monitors()[0]

    # Draw the images
    img_width_px = 960
    img_height_px = 604
    img_front = 255 * np.ones((img_height_px, img_width_px, 3), np.uint8)
    img_rear = 255 * np.ones((img_height_px, img_width_px, 3), np.uint8)
    img_left = 255 * np.ones((img_height_px, img_width_px, 3), np.uint8)
    img_right = 255 * np.ones((img_height_px, img_width_px, 3), np.uint8)
    imageParams = draw.Image.Params(_colorMap=colorMap)

    drawer_front.draw(img_front, 0, _params=imageParams)
    drawer_rear.draw(img_rear, 0, _params=imageParams)
    drawer_left.draw(img_left, 0, _params=imageParams)
    drawer_right.draw(img_right, 0, _params=imageParams)

    # Undistort
    cam_front = scene.get_camera("CAM_FRONT", compute_remaps=True)
    cam_rear = scene.get_camera("CAM_REAR", compute_remaps=True)
    cam_left = scene.get_camera("CAM_LEFT", compute_remaps=True)
    cam_right = scene.get_camera("CAM_RIGHT", compute_remaps=True)

    img_front_und = cam_front.undistort_image(img_front)
    img_rear_und = cam_rear.undistort_image(img_rear)
    img_left_und = cam_left.undistort_image(img_left)
    img_right_und = cam_right.undistort_image(img_right)

    # Draw the text
    textImg = frameInfoDrawer.draw(0,
                                   cols=400,
                                   rows=img_height_px * 2,
                                   _params=imageParams)

    mosaic = np.vstack((np.hstack(
        (img_front, img_right)), np.hstack((img_left, img_rear))))
    cv.line(mosaic, (mosaic.shape[1] // 2, 0),
            (mosaic.shape[1] // 2, mosaic.shape[0]), (0, 0, 0), 3)
    cv.line(mosaic, (0, mosaic.shape[0] // 2),
            (mosaic.shape[1], mosaic.shape[0] // 2), (0, 0, 0), 3)

    mosaic_und = np.vstack((np.hstack(
        (img_front_und, img_right_und)), np.hstack(
            (img_left_und, img_rear_und))))
    cv.line(mosaic_und, (mosaic_und.shape[1] // 2, 0),
            (mosaic_und.shape[1] // 2, mosaic_und.shape[0]), (0, 0, 0), 3)
    cv.line(mosaic_und, (0, mosaic_und.shape[0] // 2),
            (mosaic_und.shape[1], mosaic_und.shape[0] // 2), (0, 0, 0), 3)

    # Draw the top view
    topview_width = 1280
    topview_height = 1280
    ar = topview_width / topview_height
    rangeX = (-30.0, 30.0)
    rangeY = (-((rangeX[1] - rangeX[0]) / ar) / 2,
              ((rangeX[1] - rangeX[0]) / ar) / 2)
    topviewParams = draw.TopView.Params(colorMap=colorMap,
                                        topViewSize=(topview_width,
                                                     topview_height),
                                        background_color=255,
                                        rangeX=rangeX,
                                        rangeY=rangeY,
                                        stepX=1.0,
                                        stepY=1.0,
                                        draw_grid=False)
    drawerTopView = draw.TopView(scene,
                                 "vehicle-iso8855",
                                 params=topviewParams)

    topView = drawerTopView.draw(frameNum=0)

    cv.namedWindow("Cameras", cv.WINDOW_NORMAL)
    cv.imshow("Cameras", mosaic)
    cv.namedWindow("Cameras undistorted", cv.WINDOW_NORMAL)
    cv.imshow("Cameras undistorted", mosaic_und)
    cv.namedWindow("VCD info")
    cv.imshow("VCD info", textImg)
    cv.namedWindow("TopView", cv.WINDOW_NORMAL)
    cv.imshow("TopView", topView)
    cv.waitKey(0)

    fig1 = setupViewer.plot_setup()
    plt.show()
Esempio n. 23
0
from sys import platform

Config.set('graphics', 'resizable', False)

if platform == 'darwin':  # we are on a Mac
    # This probably means that we are testing on a personal laptop

    # settings for MBP 16" 2021
    fixed_window_size = (
        3072, 1920)  # we get this automatically now but here it is anyway
    fixed_window_size_cm = (34.5, 21.5)  # this is the important part
    pix_per_cm = 104.  # we get this automatically now but here it is anyway
elif platform == 'win32':
    # see if there is an external monitor plugged in
    from screeninfo import get_monitors
    mon = get_monitors()
    #    if len(get_monitors()) > 1 or get_monitors()[0].height == 1080:
    #        # must be an external monitor plugged in
    #        # assume that it is the ViewSonic TD2230
    #        fixed_window_size = (1920, 1080) # we get this automatically now but here it is anyway
    #        fixed_window_size_cm = (47.6, 26.8) # this is the important part
    #        pix_per_cm = 40. # we get this automatically now but here it is anyway
    #    else:
    # must just be the Surface Pro
    # These are surface pro settings
    fixed_window_size = (
        2160, 1440)  # we get this automatically now but here it is anyway
    fixed_window_size_cm = (47.6, 26.8)
    #        fixed_window_size_cm = (22.8, 15.2) # this is the important part
    pix_per_cm = 95.  # we get this automatically now but here it is anyway
    import winsound
Esempio n. 24
0
import csv
import os
import screeninfo

res_folder = 'res' + os.path.sep
monitors = [(m.x, m.y, m.width, m.height) for m in screeninfo.get_monitors()]


def read_hotkeys():
    """
    Read the hotkeys from the hotkeys.csv file.
    If it does not exists, set standard hotkeys.
    """

    if os.path.exists(res_folder + 'hotkeys.csv'):
        with open(res_folder + 'hotkeys.csv', newline='') as csvfile:
            reader = csv.reader(csvfile)
            return [row for row in reader]
    else:
        if not os.path.exists('res'):
            os.mkdir('res')
        hotkeys = [['alt', 'shift', f'{n}']
                   for n, _ in enumerate(screeninfo.get_monitors(), 1)]
        hotkeys.append(['alt', 'shift', 's'])
        hotkeys.append(['alt', 'shift', 'e'])
        return hotkeys


def write_hotkeys(hotkeys):
    """
    Write the hotkeys to the hotkeys.csv file.
Esempio n. 25
0
    'root_dir': '/home/nehla/laser_code',
    'file_name': '/home/nehla/laser_code/StA-Line_Scan-Fence.mov',
    # 'file_name': '/home/nehla/laser_code//home/nehla/laser_code/StA-Line_scan-long.MP4',
    'save_file_name': '/home/nehla/laser_code/save.mkv',
    'load_path': '',
    'img_ext': 'png',
    'binarize': 1,
    'show_img': 1,
    'n_frames': 0,
    'resize_factor': 0.8,
    'thresh': 50.0,
    'method': 0,
    'temporal_window_size': 10,
    'codec': 'H264',
}
monitors = get_monitors()
curr_monitor = str(monitors[0])
resolution = curr_monitor.split('(')[1].split('+')[0].split('x')

res_width, res_height = [int(x) for x in resolution]

print('resolution: ', resolution)
for m in get_monitors():
    print(m)

processArguments(sys.argv[1:], params)

root_dir = params['root_dir']
file_name = params['file_name']
save_file_name = params['save_file_name']
load_path = params['load_path']
Esempio n. 26
0
    def showError(self, message):
        """Display a simple error dialog.
        """
        # self.OnStop()
        showerror(self.parent.title(), message)


# START App Main()
r = RoundBtns()
dataSet = DataSet()
selectedTeam = ""
selectedRound = 0

# mpv_palyer = MPV(start_mpv=False, ipc_socket="/tmp/mpv.socket")
monitorList = get_monitors()
for m in monitorList:
    print(str(m))

# Bind to key press events with a decorator
#@mpv_player.on_event("start-file")
#def evStartFile_handler(evData):
#    setattr(dataSet, "playing", "1")

#@mpv_player.on_event("end-file")
#def evStartFile_handler(evData):
#    setattr(dataSet, "playing", "0")

ssock_file = '/tmp/sdobox.socket'
csock_file = '/tmp/sdobox.dubbing.socket'
Esempio n. 27
0
from screeninfo import get_monitors

for m in get_monitors():
    pass

SCREEN_WIDTH = m.width
SCREEN_HEIGHT = m.height
SCREEN_RESOLUTION = int(SCREEN_WIDTH / 2), int(SCREEN_HEIGHT / 2)

# Colors
COLOR_RGB_BLACK = 0, 0, 0,
def getResolutionsWindows():
    return ['{}x{}'.format(m.width, m.height) for m in get_monitors()]
Esempio n. 29
0
def init():
    # Global for Screen resolution and windows pos ...
    global s_height
    global s_win_width
    global s_win_height
    global s_win_height_offset
    m = re.findall(r'\d+', str(get_monitors()))
    if m:
        s_width = int(m[0])
        s_height = int(m[1])
    s_win_width = s_width // 6
    s_win_height = s_height // 4
    s_win_height_offset = 10
    print("Screen Resolution: (%d x %d) Win Resolution: (%d x %d)" %
          (s_width, s_height, s_win_width, s_win_height))

    # input video/image size
    global frames, vi_width, vi_height
    frames = 0
    vi_width = 0
    vi_height = 0

    # number of windows for hisrogramme
    global nwindows
    nwindows = configuration.N_WINDOWS
    # Set scale px/meter to default value
    global scale_px_width, scale_px_height
    scale_px_width = 0
    scale_px_height = 0
    lane_size_px = 0

    global cold_boot
    cold_boot = True

    # Global related to trackbar management
    global trackbar_enabled
    trackbar_enabled = False

    # Global related to region of interest trapeze ...
    global trap_bottom_width  # width of bottom edge of trapezoid, expressed as percentage of image width
    global trap_top_width  # ditto for top edge of trapezoid
    global trap_height  # height of the trapezoid expressed as percentage of image height
    global trap_warped_ratio  # ratio for perspective transform

    trap_bottom_width = configuration.TRAP_BOTTOM_WIDTH
    trap_top_width = configuration.TRAP_TOP_WIDTH
    trap_height = configuration.TRAP_HEIGHT
    trap_warped_ratio = configuration.TRAP_WARPED_RATIO
    """
    Global Variables for method relative to canny + HoughP
    """
    # Gaussian smoothing
    global kernel_size
    kernel_size = 3

    # Canny Edge Detector
    global low_threshold
    global high_threshold
    low_threshold = 50
    high_threshold = 150

    # Hough Transform
    global rho  # (2 -> 0.8) distance resolution in pixels of the Hough grid
    global theta  # angular resolution in radians of the Hough grid
    global threshold  # (15 -> 25) minimum number of votes (intersections in Hough grid cell)
    global min_line_length  # (10 -> 50) minimum number of pixels making up a line
    global max_line_gap  # (20 -> 200) maximum gap in pixels between connectable line segments

    rho = 2
    theta = 1 * np.pi / 180
    threshold = 15
    min_line_length = 10
    max_line_gap = 20
    """
    Global Variable for method relative to combined threshold + birdview + curves
    """
    # Filter combination
    global combined_filter_type
    combined_filter_type = configuration.FILTER_SOBEL_MAG_DIR_HLS_HSV

    # Sobel Threshold
    global sobel_th_min
    global sobel_th_max
    sobel_th_min = 50
    sobel_th_max = 255

    # Sobel Kernel Size
    global mag_sobel_kernel_size
    mag_sobel_kernel_size = 3
    global dir_sobel_kernel_size
    dir_sobel_kernel_size = 15

    # HLS threshold
    global hls_s_th_min
    global hls_s_th_max
    hls_s_th_min = 100
    hls_s_th_max = 2555

    # RGB mak
    global rgb_lower_white, rgb_upper_white
    rgb_lower_white = np.array([200, 200, 200])
    rgb_upper_white = np.array([255, 255, 255])

    # HSV mask
    # gimp uses H = 0-360, S = 0-100 and V = 0-100. But OpenCV uses  H: 0 - 180, S: 0 - 255, V: 0 - 255
    global hsv_lower_white, hsv_upper_white
    hsv_lower_white = np.array([0, 0, 184])
    hsv_upper_white = np.array([180, 16, 255])
    global hsv_lower_yellow, hsv_upper_yellow
    hsv_lower_yellow = np.array([20, 68, 95])
    hsv_upper_yellow = np.array([30, 255, 255])

    # Line curves global varaibles
    global window_size  # how many frames for line smoothing
    global left_line
    global right_line
    global detected  # did the fast line fit detect the lines?
    global left_curve, right_curve  # radius of curvature for left and right lanes
    global left_lane_inds, right_lane_inds  # for calculating curvature

    window_size = 5
    left_line = Line(n=window_size)
    right_line = Line(n=window_size)
    left_line.reset_fit()
    right_line.reset_fit()
    detected = False
    left_curve, right_curve = 0., 0.
    left_lane_inds, right_lane_inds = None, None

    # Detection mode
    global detect_mode, detect_fast_mode_allowed
    detect_fast_mode_allowed = False
    detect_mode = configuration.SLOW_MODE

    # Viz Degraded Mode
    global degraded_viz_mode_allowed, degraded_viz_mode, degraded_viz_count, degraded_viz_threshold, span_y_ratio_threshold
    degraded_viz_mode_allowed = False
    degraded_viz_mode = False
    degraded_viz_threshold = configuration.DEGRAD_VIZ_THRESHOLD
    degraded_viz_count = 0
    span_y_ratio_threshold = 1 / 2

    # PID parameters
    global Kp, Ki, Kd
    #Kp = 10
    #Ki = 1
    #Kd = 100
    Kp = 0.1
    Ki = 0.
    Kd = 0.1
    global integral, lastError, derivative
    integral = 0  # the place where we will store our integral
    lastError = 0  # the place where we will store the last error value
    derivative = 0  # the place where we will store the derivative
    """
    Global Variable for camera calibration
    """
    global mtx
    global dist

    with open(
            os.path.dirname(os.path.abspath(inspect.stack()[0][1])) +
            '/calibrate_camera.p', 'rb') as f:
        save_dict = pickle.load(f)
    mtx = save_dict['mtx']
    dist = save_dict['dist']
    print('mtx:', mtx)
    print('dist:', dist)
    """
    Global Variable for shadow removal
    """
    class ShadowProperties(object):
        light_threshold = {'automatic': 1, 'min': 0, 'max': 255}
        sat_threshold = {'automatic': 1, 'min': 0, 'max': 255}
        mask_refine_parameters = {
            'kernel_dilate_x': 15,
            'kernel_dilate_y': 15,
            'roi_max': 0
        }
        mask_blur = {'kernel_blur_x': 5, 'kernel_blur_y': 5, 'alpha_coef': 200}
        background = {
            'median_blur_ksize': 25,
            'morphology_auto': 1,
            'morphology_kernel_x': 5,
            'morphology_kernel_y': 30
        }

    global shadows
    shadows = ShadowProperties
    """
    Global Variable for inverse perspective transform
    """

    class IPMProperties(object):
        camera_parameters = {
            'fu': 800,  # 1333,
            'fv': 400,  # 425,
            'alpha': 2,  # 3,
            'cu_ratio': 50,
            'cv_ratio': 0
        }
        camera_parameters_ranges = {
            'fu': [0, 6000],
            'fv': [0, 6000],
            'alpha': [0, 90],
            'cu_ratio': [0, 100],
            'cv_ratio': [0, 100]
        }
        filter_x = {
            'filter_size_x': 5,  #40, #4,
            'sx': 8  # 36 #8 # values is /10
        }
        filter_y = {
            'filter_size_y': 50,
            'sy': 15  #48 #30 #200, # values is /10
        }
        threshold = {
            'percentile': 97  #92 #97
        }
        hough_parameters = {
            'min_distance': 7,
            'min_angle': 5,
            'max_angle': 20  # 20
        }
        hough_p_parameters = {'threshold': 25, 'line_length': 7, 'line_gap': 3}
        camera = None
        ground_transform = None

    global ipm
    ipm = IPMProperties
import numpy as np
import argparse
import cv2
import imutils
import time
import pyautogui
import time
# import pygame
# import pygame.camera
import threading

pyautogui.FAILSAFE = False
import screeninfo
# pygame.init()
# pygame.camera.init()
screen = screeninfo.get_monitors()[0]
# define the lower and upper boundaries of the "green"
# ball in the HSV color space, then initialize the
# list of tracked points
greenLower = (45, 120, 65)
greenUpper = (64, 255, 255)
pts = deque(maxlen=2)

vs = VideoStream(src=0).start()
# allow the camera or video file to warm up
time.sleep(2.0)
# keep looping
#clock = pygame.time.Clock()


def function(hsv):
Esempio n. 31
0
def main():
    """Application entry point"""

    if os.geteuid() == 0:
        sys.exit("This software is not supposed to be run as root!")

    io1_io2_layout = []
    io3_io4_layout = []
    ioexp_layout = []
    modbus_rx_len = 0

    global modbus_request
    global DEFAULT_UART_PORT
    global SCREEN_POS_X
    global SCREEN_POS_Y

    # Get center position coordinates of monitor
    for monitor in get_monitors():
        SCREEN_POS_X = int(monitor.width / 2)
        SCREEN_POS_Y = int(monitor.height / 2)
        break

    # Check platform support
    if "linux" in platform.system().lower():
        DEFAULT_UART_PORT = "/dev/ttyACM0"
    elif "windows" in platform.system().lower():
        DEFAULT_UART_PORT = "COM1"
    else:
        sg.Popup('OS not supported!', location=(SCREEN_POS_X, SCREEN_POS_Y))
        sys.exit(1)

    # Open connection to slave microcontroller
    while True:
        connection_settings = gui_connection_popup()
        if not connection_settings:
            sys.exit(0)

        [_type, opt1, opt2] = connection_settings
        try:
            if _type == 'uart':
                dev_con = DeviceConnection(mode='uart_usb', port=opt1)
            else:
                dev_con = DeviceConnection(mode='i2c',
                                           address=Convert.str_to_int(opt1),
                                           bus=Convert.str_to_int(opt2))
            break
        except Exception as msg:
            sg.Popup('Connection failed!',
                     location=(SCREEN_POS_X, SCREEN_POS_Y))

    # Get board hardware info
    hwinfo_reg = dev_con.get_register(REG.R_HW_INFO)
    board_type = ((hwinfo_reg & 0xF000) >> 12)
    board_variant = ((hwinfo_reg & 0x0F00) >> 8)

    # Set options depending on variant
    rtc_supported = (board_type == BOARD_TYPE.AUTOMATE_MINI
                     and board_variant == BOARD_VARIANT.FULL)
    rs485_supported = (board_type == BOARD_TYPE.AUTOMATE_MINI
                       and board_variant == BOARD_VARIANT.FULL)
    can_supported = (board_type == BOARD_TYPE.AUTOMATE_MINI
                     and board_variant == BOARD_VARIANT.FULL)

    if board_type != BOARD_TYPE.AUTOMATE_MINI:
        sys.exit("Board not supported by this tool!")

    def gui_update_tab(reg_address_start, reg_address_stop):
        """Get / update all registers for range"""

        reg_values = dev_con.get_registers(
            reg_address_start, reg_address_stop - reg_address_start + 1)
        for i in range(reg_address_start, reg_address_stop + 1):
            if str('_KEY_TEXT_%i' % i) in gui_window.AllKeysDict:
                if not values[str('_KEY_EDIT_%i' % i)]:
                    gui_window[str(
                        '_KEY_TEXT_%i' % i)].update(value=format_response(
                            i, reg_values[i - reg_address_start], values))

    def gui_update_tab_modbus_dmx512():
        """Get / update all modbus and DMX512 registers"""

        global modbus_request

        modbus_enabled = 'modbus' in values[str(
            '_KEY_TEXT_%s' % REG.RW_UART_RS485_CONF1)].lower()
        dmx512_enabled = 'dmx512' in values[str(
            '_KEY_TEXT_%s' % REG.RW_UART_RS485_CONF1)].lower()
        gui_window[GUI_KEY_MODBUS_TXBUT].update(disabled=not modbus_enabled)
        gui_window[GUI_KEY_DMX512_TXBUT].update(disabled=not dmx512_enabled)

        if modbus_enabled and modbus_request:
            modbus_request_mode = (values[GUI_KEY_MODBUS_CODE] == str(4)
                                   or values[GUI_KEY_MODBUS_CODE] == str(3)
                                   )  # TODO support for function 1 and 2?
            gui_window[GUI_KEY_MODBUS_REG_VAL].update(
                disabled=modbus_request_mode)
            gui_window[GUI_KEY_MODBUS_REG_LEN].update(
                disabled=not modbus_request_mode)
            rx_state = dev_con.get_register(REG.R_UART_RS485_RX_STATUS)

            if UART_STATE(rx_state) == UART_STATE.STATE_OK:
                rx_len = dev_con.get_register(REG.R_UART_RS485_RX_PEND)
                dev_con.set_register(REG.W_UART_RS485_RX_LEN, rx_len)
                gui_window[GUI_KEY_MODBUS_RESP].update(value=str(
                    dev_con.get_registers(REG.R_UART_RS485_RX_VAL,
                                          register_len=int(rx_len / 2))))
                modbus_request = False
            else:
                gui_window[GUI_KEY_MODBUS_RESP].update(
                    value=str(UART_STATE(rx_state).name))

    def gui_update_canrx():
        """Get / update can RX messages"""

        reg_start = REG.R_CAN_RX_STATUS
        reg_stop = REG.R_CAN_RX_ERRCNT

        while True:
            reg_values = dev_con.get_registers(reg_start,
                                               reg_stop - reg_start + 1)
            for i in range(reg_start, reg_stop + 1):
                if str('_KEY_TEXT_%i' % i) in gui_window.AllKeysDict:
                    if not values[str('_KEY_EDIT_%i' % i)]:
                        gui_window[str(
                            '_KEY_TEXT_%i' % i)].update(value=format_response(
                                i, reg_values[i - reg_start], values))

            if int(reg_values[REG.R_CAN_RX_PEND - reg_start]) > 0:

                frame_txt = str(datetime.datetime.now().time())

                can_id = int(reg_values[REG.R_CAN_RX_ID2 - reg_start])
                can_data_len = int(reg_values[REG.R_CAN_RX_LEN - reg_start])

                # ID1 is only used for the upper 13-bits of an extended 29-bit id scheme
                # All bits are set if the received frame is the regular format (11-bit id)
                if int(reg_values[REG.R_CAN_RX_ID1 - reg_start]) != 0xFFFF:
                    can_id += (
                        int(reg_values[REG.R_CAN_RX_ID1 - reg_start]) << 16)
                    frame_txt += str(" - Extended ID: %08X Data: " % can_id)
                else:
                    frame_txt += str(" - ID: %03X Data: " % can_id)

                for i in range(4):
                    if can_data_len <= 0:
                        break

                    frame_txt += str(
                        "%02X " %
                        ((int(reg_values[REG.R_CAN_RX_DATA1 - reg_start + i])
                          & 0xFF00) >> 8))
                    can_data_len -= 1

                    if can_data_len <= 0:
                        break

                    frame_txt += str(
                        "%02X " %
                        ((int(reg_values[REG.R_CAN_RX_DATA1 - reg_start + i])
                          & 0x00FF) >> 0))
                    can_data_len -= 1

                gui_window[GUI_KEY_CAN_LOG +
                           sg.WRITE_ONLY_KEY].print(frame_txt)

                # Even more frames in FIFO buffer, read them now
                if int(reg_values[REG.R_CAN_RX_PEND - reg_start]) > 1:
                    continue

            break

    # Build GUI tab layout
    gui_layout_tabs = []
    uart_layout = gui_format_tab(REGMAP.REG_MAP_UART)
    uart_layout.append([sg.Text('')])
    uart_layout.append([
        sg.Text(
            'RS485 Modbus RTU Master/Client (Requires UART in modbus mode)')
    ])
    uart_layout.append([
        sg.Text('Slave address (1-255)', size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.In('1',
              disabled=False,
              key=GUI_KEY_MODBUS_SLAVE,
              size=(CONF_REG_VALUE_WIDTH, 1),
              enable_events=True)
    ])
    uart_layout.append([
        sg.Text('Function code (3, 4 or 16)',
                size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.In('4',
              disabled=False,
              key=GUI_KEY_MODBUS_CODE,
              size=(CONF_REG_VALUE_WIDTH, 1),
              enable_events=True)
    ])
    uart_layout.append([
        sg.Text('Register address', size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.In('1',
              disabled=False,
              key=GUI_KEY_MODBUS_REG,
              size=(CONF_REG_VALUE_WIDTH, 1),
              enable_events=True)
    ])
    uart_layout.append([
        sg.Text('Register count', size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.In('1',
              disabled=False,
              key=GUI_KEY_MODBUS_REG_LEN,
              size=(CONF_REG_VALUE_WIDTH, 1),
              enable_events=True)
    ])
    uart_layout.append([
        sg.Text('Register value(s) (comma separated)',
                size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.In('1',
              disabled=False,
              key=GUI_KEY_MODBUS_REG_VAL,
              size=(CONF_REG_VALUE_WIDTH, 1),
              enable_events=True)
    ])
    uart_layout.append([
        sg.Text('', size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.B('Send/Request',
             key=GUI_KEY_MODBUS_TXBUT,
             enable_events=True,
             disabled=False)
    ])
    uart_layout.append([
        sg.Text('Response', size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.In(disabled=True,
              key=GUI_KEY_MODBUS_RESP,
              size=(CONF_REG_VALUE_WIDTH, 1),
              enable_events=True)
    ])
    uart_layout.append([sg.Text('')])
    uart_layout.append(
        [sg.Text('RS485 DMX512 (Requires UART in DMX512 mode)')])
    uart_layout.append([
        sg.Text('Start channel/slot (1-512)',
                size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.In('1',
              key=GUI_KEY_DMX512_SLOT,
              size=(CONF_REG_VALUE_WIDTH, 1),
              enable_events=True)
    ])
    uart_layout.append([
        sg.Text('Value(s) (comma separated, 0-255)',
                size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.In('0',
              key=GUI_KEY_DMX512_TXVAL,
              size=(CONF_REG_VALUE_WIDTH, 1),
              enable_events=True)
    ])
    uart_layout.append([
        sg.Text('', size=(CONF_REG_MODBUS_DESC_WIDTH, 1)),
        sg.B('Send', key=GUI_KEY_DMX512_TXBUT, enable_events=True)
    ])

    gui_layout_tabs.append(
        sg.Tab('General',
               gui_format_tab(REGMAP.MAP_GEN_INFO),
               tooltip='Generic device info',
               key=GUI_TABKEY_GEN_INFO))

    gui_layout_tabs.append(
        sg.Tab('IO1', gui_format_tab(REGMAP.MAP_IO_1), key=GUI_TABKEY_IO1))
    gui_layout_tabs.append(
        sg.Tab('IO2', gui_format_tab(REGMAP.MAP_IO_2), key=GUI_TABKEY_IO2))
    gui_layout_tabs.append(
        sg.Tab('IO3', gui_format_tab(REGMAP.MAP_IO_3), key=GUI_TABKEY_IO3))
    gui_layout_tabs.append(
        sg.Tab('IO Expander',
               gui_format_tab(REGMAP.MAP_IO_EXP),
               key=GUI_TABKEY_IO_EXP))

    # Add RS485, RTC and CAN bus tabs only if supported by board
    if rs485_supported:
        gui_layout_tabs.append(
            sg.Tab('RS485',
                   uart_layout,
                   tooltip='UART and RS485 settings',
                   key=GUI_TABKEY_UART))
    if can_supported:
        gui_layout_tabs.append(
            sg.Tab('CAN bus Config',
                   gui_format_tab(REGMAP.REG_MAP_CAN_CONF),
                   tooltip='CAN bus Config',
                   key=GUI_TABKEY_CAN_CONF))
        gui_layout_tabs.append(
            sg.Tab('CAN bus TX',
                   gui_format_tab(REGMAP.REG_MAP_CAN_TX),
                   tooltip='CAN bus TX',
                   key=GUI_TABKEY_CAN_TX))
        can_rx_layout = gui_format_tab(REGMAP.REG_MAP_CAN_RX)
        can_rx_layout.append([sg.Text('')])
        can_rx_layout.append([
            sg.Text('Receive log', size=(CONF_REG_MODBUS_DESC_WIDTH, 15)),
            sg.MLine('',
                     size=(CONF_REG_VALUE_WIDTH, 15),
                     key=GUI_KEY_CAN_LOG + sg.WRITE_ONLY_KEY)
        ])
        gui_layout_tabs.append(
            sg.Tab('CAN bus RX',
                   can_rx_layout,
                   tooltip='CAN bus RX',
                   key=GUI_TABKEY_CAN_RX))
    if rtc_supported:
        gui_layout_tabs.append(
            sg.Tab('RTC',
                   gui_format_tab(REGMAP.MAP_RTC),
                   tooltip='Real time clock',
                   key=GUI_TABKEY_RTC))

    gui_layout_tabs.append(
        sg.Tab('Advanced settings',
               gui_format_tab(REGMAP.REG_MAP_ADVANCED),
               tooltip='Advanced settings',
               key=GUI_TABKEY_ADVANCED))
    gui_layout_tabs.append(
        sg.Tab('Expert settings',
               gui_format_tab(REGMAP.REG_MAP_EXPERT_ZONE),
               tooltip='Expert settings',
               key=GUI_TABKEY_EXPERT))

    gui_layout = [[
        sg.TabGroup([gui_layout_tabs], tooltip='', key='_TABGROUP_')
    ]]

    # Show the layout on screen
    gui_window = sg.Window('AutoMATE Slave Control',
                           gui_layout,
                           size=(1170, 800),
                           location=get_window_location(1170, 900))

    # Poll registers continuously for updates
    while True:
        event, values = gui_window.read(timeout=250)
        if event in (sg.WIN_CLOSED, 'Quit'):
            break

        # Enable/disable register edit mode
        if event.startswith('_KEY_EDIT_'):
            index = event.split('_KEY_EDIT_')[1]
            if str('_KEY_CONF_%s' % index) in gui_window.AllKeysDict:
                gui_window[str('_KEY_CONF_%s' %
                               index)].update(disabled=(not values[event]))
                if not values[event]:
                    gui_window[str('_KEY_WRITE_%s' %
                                   index)].update(disabled=True)
            else:
                gui_window[str('_KEY_TEXT_%s' %
                               index)].update(disabled=(not values[event]))
                gui_window[str('_KEY_WRITE_%s' %
                               index)].update(disabled=(not values[event]))

        # Open register configuration popup window
        elif event.startswith('_KEY_CONF_'):

            index = int(event.split('_KEY_CONF_')[1])
            register_value = 0

            # Enable write button
            gui_window[str('_KEY_WRITE_%s' % index)].update(disabled=False)

            # Write local IO1-IO4 GPIO configuration registers
            if REG.RW_GPIO1_CONF1 <= index <= REG.RW_GPIO4_CONF1:

                response = gui_config_popup([
                    GPIO_MODE, GPIO_PULL, GPIO_THR, GPIO_HYST, GPIO_POL,
                    GPIO_FILT
                ])

                if response:
                    register_value |= (response[0] << 13)
                    register_value |= (response[1] << 11)
                    register_value |= (response[2] << 4)
                    register_value |= (response[3] << 0)
                    register_value |= (response[4] << 10)
                    register_value |= (response[5] << 8)

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write local IO1-IO4 function configuration registers
            elif REG.RW_GPIO1_CONF2 <= index <= REG.RW_GPIO4_CONF2:

                response = gui_config_popup([GPIO_FUNC])

                if response:
                    register_value = response[0]

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write LED configuration register
            elif index == REG.RW_LED_CONF:

                response = gui_config_popup([LED_MODE])

                if response:
                    register_value |= (response[0] << 0)

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write local UART configuration registers
            elif index == REG.RW_UART_RS485_CONF1 or \
                    index == REG.RW_UART_MIKRO2_CONF1:

                response = gui_config_popup(
                    [UART_MODE, UART_STOPBITS, UART_PARITY])

                if response:

                    register_value |= (response[0] << 8)
                    register_value |= (response[1] << 6)
                    register_value |= (response[2] << 4)

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write I2C configuration register
            elif index == REG.RW_I2C_CONF:

                response = gui_config_popup([I2C_ADDR_CNT, I2C_START_ADDR])

                if response:
                    register_value |= (response[0] << 8)
                    register_value |= (response[1] << 0)

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write emulator configuration register
            elif index == REG.RW_EMU_CONF:

                response = gui_config_popup([EMU_RTC, EMU_IOEXP])

                if response:
                    register_value |= (response[0] << 1)
                    register_value |= (response[1] << 0)

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write LED EEPROM register
            elif index == REG.W_LED_SAVE:

                response = gui_config_popup([SAVE_LED_CONF])

                if response:
                    register_value = response[0]

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write UART EEPROM register
            elif index == REG.W_UART_SAVE:

                response = gui_config_popup([SAVE_UART_CONF])

                if response:
                    register_value = response[0]

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write GPIO EEPROM register
            elif index == REG.W_GPIO_SAVE:

                response = gui_config_popup([SAVE_IO_CONF])

                if response:
                    register_value = response[0]

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write bootloader register
            elif index == REG.W_BOOTLOADER:

                response = gui_config_popup([BOOTLOADER_RESET])

                if response:
                    register_value = response[0]

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write UART and USB switch state
            elif index == REG.RW_SWITCH_CONF:

                response = gui_config_popup([SWITCH_UART])

                if response:
                    register_value = response[0]

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write CAN config register
            elif index == REG.RW_CAN_CONF1:

                response = gui_config_popup([CAN_MODE])

                if response:
                    register_value |= (response[0] << 8)

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

            # Write CAN baudrate
            elif index == REG.RW_CAN_CONF2:

                response = gui_config_popup([CAN_BAUDRATE])

                if response:
                    register_value = response[0]

                    gui_window[str('_KEY_TEXT_%i' %
                                   index)].update(value=format_response(
                                       index, register_value, values, False))

        elif event.startswith(GUI_KEY_MODBUS_TXBUT):
            gui_window[GUI_KEY_MODBUS_RESP].update(value='pending...')

            tx_values = values[GUI_KEY_MODBUS_REG_VAL]
            if ',' in tx_values:
                tx_values = tx_values.split(',')
            else:
                tx_values = [tx_values]

            tx_values = [Convert.str_to_int(tx_val) for tx_val in tx_values]

            modbus_message = Modbus.build_rtu_frame(
                function_code=Convert.str_to_int(values[GUI_KEY_MODBUS_CODE]),
                slave_address=Convert.str_to_int(values[GUI_KEY_MODBUS_SLAVE]),
                register_address=Convert.str_to_int(
                    values[GUI_KEY_MODBUS_REG]),
                register_count=Convert.str_to_int(
                    values[GUI_KEY_MODBUS_REG_LEN]),
                values=tx_values)

            print(modbus_message)
            dev_con.set_registers(modbus_message[0],
                                  modbus_message[1],
                                  format_bytes=True)

            modbus_request = True

        elif event.startswith(GUI_KEY_DMX512_TXBUT):

            tx_values = values[GUI_KEY_DMX512_TXVAL]
            if ',' in tx_values:
                tx_values = tx_values.split(',')
            else:
                tx_values = [tx_values]

            tx_values = [Convert.str_to_int(tx_val) for tx_val in tx_values]

            [response_len, dmx512_message] = Dmx512.build_dmx512_frame(
                slot=Convert.str_to_int(values[GUI_KEY_DMX512_SLOT]),
                values=tx_values)

            print(dmx512_message)
            print(modbus_rx_len)
            dev_con.set_registers(dmx512_message[0],
                                  dmx512_message[1],
                                  format_bytes=True)

        # Write modified register to device
        elif event.startswith('_KEY_WRITE_'):
            index = event.split('_KEY_WRITE_')[1]

            # Send to hardware device
            try:
                dev_con.set_register(
                    int(index),
                    Convert.str_to_int(values[str('_KEY_TEXT_%s' %
                                                  index)].strip()))
            except ValueError:
                sg.Popup('Oops!',
                         'Only numbers are accepted!',
                         location=(SCREEN_POS_X, SCREEN_POS_Y))

            # I2C slave needs some time to re-initialize
            if int(index) == REG.RW_I2C_CONF:
                time.sleep(1)
                new_addr = Convert.str_to_int(values[str(
                    '_KEY_TEXT_%s' % index)]) & 0x000F
                dev_con.address = I2C_START_ADDR.to_address_value(
                    I2C_START_ADDR(new_addr).name)

            # Disable edit mode again after transmit
            gui_window[str('_KEY_EDIT_%s' % index)].update(value=False)
            gui_window[str('_KEY_TEXT_%s' % index)].update(disabled=True)
            gui_window[str('_KEY_WRITE_%s' % index)].update(disabled=True)
            if str('_KEY_CONF_%s' % index) in gui_window.AllKeysDict:
                gui_window[str('_KEY_CONF_%s' % index)].update(disabled=True)

        if values['_TABGROUP_'] == GUI_TABKEY_IO1 or \
                values['_TABGROUP_'] == GUI_TABKEY_IO2 or \
                values['_TABGROUP_'] == GUI_TABKEY_IO3:
            gui_update_tab(REG.R_GPIO1_ADC_VAL, REG.R_GPIO4_ADC_VAL)
            gui_update_tab(REG.RW_GPIO1_DAC_VAL, REG.RW_GPIO4_DAC_VAL)
            gui_update_tab(REG.RW_GPIO1_DIG_VAL1, REG.RW_GPIO4_DIG_VAL1)
            gui_update_tab(REG.RW_GPIO1_DIG_VAL2, REG.RW_GPIO4_DIG_VAL2)
            gui_update_tab(REG.RW_GPIO1_DIG_VAL3, REG.RW_GPIO4_DIG_VAL3)
            gui_update_tab(REG.RW_GPIO1_CONF1, REG.RW_GPIO4_CONF2)

        elif values['_TABGROUP_'] == GUI_TABKEY_IO_EXP:
            gui_update_tab(REG.RW_GPAB_IODIR, REG.RW_GPAB_GPPD)
            gui_update_tab(REG.RW_GPAB_DIG_VAL1, REG.RW_GPAB_DIG_VAL1)

        elif values['_TABGROUP_'] == GUI_TABKEY_RTC:
            gui_update_tab(REG.RW_RTC_SEC_VAL, REG.RW_RTC_WDAY_VAL)

        elif values['_TABGROUP_'] == GUI_TABKEY_CAN_CONF:
            gui_update_tab(REG.RW_CAN_CONF1, REG.RW_CAN_FILT2_LOW)

        elif values['_TABGROUP_'] == GUI_TABKEY_CAN_RX:
            gui_update_canrx()

        elif values['_TABGROUP_'] == GUI_TABKEY_CAN_TX:
            gui_update_tab(REG.R_CAN_TX_STATUS, REG.R_CAN_TX_ERRCNT)

        elif values['_TABGROUP_'] == GUI_TABKEY_GEN_INFO:
            gui_update_tab(REG.R_SW_INFO, REG.R_SWITCH_VAL)
            gui_update_tab(REG.R_GPIO_M1_AN_ADC_VAL, REG.R_GPIO_M2_AN_ADC_VAL)
            gui_update_tab(REG.RW_LED_CONF, REG.RW_LED_CONF)
            gui_update_tab(REG.R_GEN_ERROR1, REG.R_GEN_ERROR2)

        elif values['_TABGROUP_'] == GUI_TABKEY_NETWORK:
            gui_update_tab(REG.RW_NET_CONF_IP1, REG.RW_NET_CONF_DHCP)

        elif values['_TABGROUP_'] == GUI_TABKEY_UART:
            gui_update_tab(REG.RW_UART_RS485_CONF1, REG.RW_UART_MIKRO2_CONF2)
            gui_update_tab_modbus_dmx512()

        elif values['_TABGROUP_'] == GUI_TABKEY_ADVANCED:
            gui_update_tab(REG.RW_EMU_CONF, REG.RW_SWITCH_CONF)
            gui_update_tab(REG.R_GPIO1_CUR, REG.R_GPIO4_CUR)

        elif values['_TABGROUP_'] == GUI_TABKEY_EXPERT:
            gui_update_tab(REG.R_DEBUG1, REG.RW_ESP32_DELAY)

    dev_con.disconnect()
    gui_window.close()
Esempio n. 32
0
import screeninfo
print()
print(screeninfo.get_monitors())

# from screeninfo import get_monitors
# print(get_monitors())
# for data in get_monitors():
#     print(data)
Esempio n. 33
0
    def handle_input(self, keyset):
        """ Handle pygame input events
        """
        
        poll = pygame.event.poll
        
        event = poll()
        while event:
            if event.type == QUIT:
                self.running = False
                pygame.quit()
                break

            elif event.type == KEYDOWN:
                

                if keyset == "game":
                    if event.key == K_EQUALS:
                        self.map_layer.zoom += .25

                    elif event.key == K_MINUS:
                        value = self.map_layer.zoom - .25
                        if value > 0:
                            self.map_layer.zoom = value
                        else:
                            self.map_layer.zoom = 0.1

                    elif event.key == K_KP0:
                        try:
                            if self.switcher() == True:
                                self.generate_surrounding_maps()
                        except FileNotFoundError:
                            print("Exception Caught")
                        pass

                    elif event.key == K_e:
                        self.menu = "inventory"
                        pass

                    if event.key == K_ESCAPE:
                        for i in attack_stats_types:
                            stats[i] = attack_stats[i]
                        pickle.dump(stats, open(os.path.join("data", "saves", "save.dat"), "wb"))
                        pickle.dump(inventory, open(os.path.join("data", "saves", "inventory.dat"), "wb"))
                        self.running = False
                        pygame.quit()
                        print(" ")
                        sleep(0.5)
                        print("Shutdown... Complete")
                        sys.exit()
                        break

                if keyset != "game":
                    if event.key == K_ESCAPE:
                        self.menu = "game"
                        pass

                if keyset == "inventory":
                    if event.key == K_r:
                        self.genchests()

                if keyset == "chest":
                    if event.key == K_r:
                        chestContents[self.chestNo] = self.genchests()

                    if event.key == K_t:
                        if taken[self.chestNo] != True:
                            self.takeChest()
                            taken[self.chestNo] = True
                            pickle.dump(taken, open(os.path.join("data", "saves", "taken.dat"), "wb"))

                if keyset == "attack":
                    pass

                #Basically just debug keys
                if event.key == K_KP1:
                    self.menu = "game"
                    pass

                elif event.key == K_KP2:
                    self.map_change(FOREST)
                    self.map = "forest"

                elif event.key == K_KP3:
                    self.generate_new_map(4, 16, 3)
                    pass

                elif event.key == K_KP4:
                    self.map_generate(str(self.grid[0]) +", "+ str(self.grid[1]) +".tmx", 4, 16.0, self.grid[0], self.grid[1])  
                    pass

                elif event.key == K_KP5:
                    self.enemy_stats = self.gen_enemy(attack_stats, enemy_stats)
                    self.menu = "attack"
                    pass

                elif event.key == K_KP6:
                    print("X :" +str(int(self.hero.position[0])) +
                          ", Y: " +str(int(self.hero.position[1])) +
                          ", Map: "+ self.map)
                    pass

                elif event.key == K_KP7:
                    print(str(pygame.mouse.get_pos()))
                    pass
                
                elif event.key == K_KP8:
                    sleep(0.5)

                elif event.key == K_KP9:
                    editor = db_interface.Editor()
                    conn = sqlite3.connect('data/saves/data.db')
                    c = conn.cursor()

                    for var in vars:
                        exec("del "+var+"[:]")
                        for data in c.execute("SELECT {} FROM csv".format(var)):
                            data = str(data[0])
                            exec("{}.append(\"{}\")".format(var, data))
                            pass

                elif event.key == K_F11:
                    for m in screeninfo.get_monitors():
                        displ = str(m)
                        w, h, mx, c = displ.split(", ")
                        
                    if self.fullscreen:
                        self.fullscreen = False
                        screen = init_screen(1024, 700, pygame.HWSURFACE | pygame.FULLSCREEN )
                    else:
                        self.fullscreen = True
                        screen = init_screen(w, h, pygame.HWSURFACE | pygame.RESIZABLE )

                    pygame.display.toggle_fullscreen()

            elif event.type == VIDEORESIZE:
                self.map_layer.set_size((event.w, event.h))
                dispHeight = event.h
                dispWidth = event.w
                

            event = poll()

        # using get_pressed is slightly less accurate than testing for events
        # but is much easier to use.
        if keyset == "game":
            pressed = pygame.key.get_pressed()
            if pressed[K_UP]:
                self.hero.velocity[1] = -HERO_MOVE_SPEED
                self.direction = "up"
                self.direction2 = "up"
            elif pressed[K_DOWN]:
                self.hero.velocity[1] = HERO_MOVE_SPEED
                self.direction = "down"
                self.direction2 = "down"
            elif pressed[K_w]:
                self.hero.velocity[1] = -HERO_SPRINT_SPEED
                self.direction = "up"
                self.direction2 = "up"
            elif pressed[K_s]:
                self.hero.velocity[1] = HERO_SPRINT_SPEED
                self.direction = "down"
                self.direction2 = "down"
            else:
                self.hero.velocity[1] = 0
                self.direction2 = "still"
            if pressed[K_LEFT]:
                self.hero.velocity[0] = -HERO_MOVE_SPEED
                self.direction = "left"
                self.direction1 = "left"
            elif pressed[K_RIGHT]:
                self.hero.velocity[0] = HERO_MOVE_SPEED
                self.direction = "right"
                self.direction1 = "right"
            elif pressed[K_a]:
                self.hero.velocity[0] = -HERO_SPRINT_SPEED
                self.direction = "left"
                self.direction1 = "left"
            elif pressed[K_d]:
                self.hero.velocity[0] = HERO_SPRINT_SPEED
                self.direction = "right"
                self.direction1 = "right"
            else:
                self.hero.velocity[0] = 0
                self.direction1 = "still"

            if self.direction1 == "still" and self.direction2 == "still":
                self.direction = "still"
Esempio n. 34
0
 def __init__(self):
     self.monitors = get_monitors()
Esempio n. 35
0
def main():
	while(True):
		namedWindow('map', WND_PROP_FULLSCREEN)
		setWindowProperty('map', WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN)

		monitor = get_monitors()[0]
		map_rect = Rectangle(0, 0, monitor.width, monitor.height)
		#map_rect = Rectangle(0, 0, 800, 800)

		options = zeros((map_rect.height, map_rect.width, 2), dtype=uint32)

		row = arange(0, options.shape[1])
		col = arange(0, options.shape[0])
		options[:, :, 0] = row
		for c in row:
			options[:, c, 1] = col

		options = options.reshape((options.shape[0] * options.shape[1], 2))


		#start = (100, 100)
		#end = (750, 750)
		start = random_point(map_rect)
		end = random_point(map_rect)
		max_segment = 20

		map = zeros((map_rect.height, map_rect.width, 3), dtype=uint8)
		circle(map, start, 5, (10, 255, 10), 3)
		circle(map, end, 5, (100, 100, 255), 3)

		root = Node(None, start, 0)
		node_hash = {start:root}

		num_obstacles = 12
		obstacles = []

		obstacle_hash = zeros(map.shape[:2], dtype=uint8)

		for i in range(num_obstacles):
			while True:
				top_left = random_point(map_rect)
				bottom_right = random_point(Rectangle.create_from_points(top_left, map_rect.bottom_right))
				obstacle = Rectangle.create_from_points(top_left, bottom_right)

				if not rect_has_intersection(obstacle_hash, obstacle) and not obstacle.contains_point(start, 20) and not obstacle.contains_point(end, 20):
					obstacles.append(obstacle)
					break

			rectangle(obstacle_hash, obstacle.top_left, obstacle.bottom_right, 255, 20)
			rectangle(obstacle_hash, obstacle.top_left, obstacle.bottom_right, 255, FILLED)
			rectangle(map, obstacle.top_left, obstacle.bottom_right, [255, 100, 0], 2)

		just_obstacles = map.copy()

		gauss = gaussian(size=map_rect.area / 10000)
		g_offset = gauss.shape[0] / 2 + max_segment
		unsearched_area = ones((map.shape[0] + 2 * g_offset, map.shape[1] + 2 * g_offset), dtype=float64)
		unsearched_area[g_offset:g_offset + map.shape[0], g_offset:g_offset + map.shape[1]] -= obstacle_hash / 255

		# imshow('obstacles', obstacle_hash)

		tree = kdtree.create([start])

		video_filename = "videos/vid%s.avi" % datetime.datetime.now().strftime("%Y_%m_%d_%H-%M-%S")
		video = VideoWriter(video_filename, VideoWriter_fourcc(*'IYUV'), 60, (map.shape[1], map.shape[0]))

		for i in range(3000):
			print("\r%4d" % i, end="")
			x, y = random_point(map_rect)
			#unsearched_probabilities = unsearched_area[g_offset:g_offset + map.shape[0], g_offset:g_offset + map.shape[1]]
			#x, y = random_point_with_probability(unsearched_probabilities, options)


			# circle(map, (x, y), 4, [255, 0, 255], 1)

			nn, dist = tree.search_nn((x, y))
			dist = math.sqrt(dist)
			xnn, ynn = nn.data

			if dist > max_segment:
				angle = math.atan2((xnn - x), (y - ynn)) + pi / 2.0
				# print(angle * 180 / math.pi)
				x = int(max_segment * cos(angle) + xnn)
				y = int(max_segment * sin(angle) + ynn)

			new_point = (x, y)
			#nn_point = (xnn, ynn)

			neighbors = tree.search_knn(new_point, 50)
			cumulative_costs = []
			for neighbor, distance in neighbors:
				#print("1: %s, 2: %s"%(new_point, neighbor.data))
				#square_dist = ((asarray(new_point) - asarray(neighbor.data)) ** 2).sum()
				#man_dist = math.sqrt(((asarray(new_point) - asarray(neighbor.data)) ** 2).sum())
				#print("d1: %d, d2: %d, d3: %d" % (distance, square_dist, man_dist))
				distance = math.sqrt(distance)
				distance = distance if distance < max_segment * 3 else 10000
				cumulative_costs.append(node_hash[neighbor.data].cumulative_cost + distance)

			best_neighbor_index = argmin(cumulative_costs)
			best_neighbor = node_hash[neighbors[best_neighbor_index][0].data]
			best_cumulative_cost = cumulative_costs[best_neighbor_index]

			neighbors.remove(neighbors[best_neighbor_index])

			if not line_has_intersection(obstacle_hash, best_neighbor.location, new_point):
				tree.add(new_point)
				#line(map, nn_point, new_point, [100, 0, 255], 2)

				#parent = node_hash[nn_point]
				new_node = best_neighbor.addChild(new_point, best_cumulative_cost)
				node_hash[new_point] = new_node


				for neighbor, distance in neighbors:
					neighbor_node = node_hash[neighbor.data]
					distance = math.sqrt(distance)
					if distance < max_segment * 3 and (new_node.cumulative_cost + distance) < neighbor_node.cumulative_cost:
						if not line_has_intersection(obstacle_hash, neighbor_node.location, new_node.location):
							rewire(new_node, neighbor_node, distance)
							#print("rewired")





				distance_to_end = math.sqrt(square(asarray(end) - asarray(new_point)).sum())

				"""
				if distance_to_end < 50:
					#end_node = Node(node_hash[new_point], end)
					end_node = node_hash[new_point].addChild(end, node_hash[new_point].cumulative_cost + distance_to_end)
					break
				"""

				#rect = Rectangle(new_point[0] - gauss.shape[1] / 2, new_point[1] - gauss.shape[0] / 2, gauss.shape[1], gauss.shape[0])
				#unsearched_area[rect.y + g_offset:rect.bottom_right[1] + g_offset, rect.x + g_offset:rect.bottom_right[0] + g_offset] -= gauss
				#unsearched_area = unsearched_area.clip(min=0)
				#imshow('unsearched', 1-unsearched_area)# /unsearched_area.max())

			if i % 1 == 0:
				map = draw_all_lines(just_obstacles.copy(), root)
				putText(map, "Iteration: %d" % i, (20, 20), FONT_HERSHEY_SIMPLEX, .7, (50, 255, 50))
				imshow('map', map)
				video.write(map)
				waitKey(1)
			# tree.rebalance()

			if i % 100 == 0:
				tree.rebalance()

		map = draw_all_lines(just_obstacles.copy(), root)

		neighbors = tree.search_knn(end, 30)
		closest_node = None
		best_cost = inf
		for neighbor, dist in neighbors:
			dist = math.sqrt(dist)
			node = node_hash[neighbor.data]
			if node.cumulative_cost + dist < best_cost:
				closest_node = node
				best_cost = node.cumulative_cost + dist

		current_node = closest_node.addChild(end, 0)

		while not current_node.parent is None:
			line(map, current_node.location, current_node.parent.location, (255, 255, 0), 2)
			current_node = current_node.parent
			imshow('map', map)
			video.write(map)
			waitKey(50)

		#imshow('map', map)
		#waitKey(0)

		video.write(map)

		video.release()

		time.sleep(2)
Esempio n. 36
0
    def __init__(self, parent=None):
        super(TraySetting, self).__init__(parent)
        self.setupUi(self)

        # 初始化数据
        self.__db_helper = DBHelper(self)
        self.__config_helper = ConfigHelper(self)
        self.__sql_where = self.__config_helper.get_config_key(
            self.__config_section_background, "sqlWhere")
        self.textEdit_sqlWhere.setText(self.__sql_where)
        self.__time_interval = int(
            self.__config_helper.get_config_key(
                self.__config_section_background, "timeIntervalInMin"))
        self.lineEdit_min.setText(str(self.__time_interval))

        self.__current_image = None

        self.pushButton_save.pressed.connect(self.__save)
        self.pushButton_cancel.pressed.connect(self.hide)

        # 系统托盘
        self.__tray = QtWidgets.QSystemTrayIcon()
        self.__tray.setIcon(QtGui.QIcon("images/tranIcon.png"))
        self.__tray.setToolTip("壁纸切换")
        self.__tray.activated[QSystemTrayIcon.ActivationReason].connect(
            self.__on_tray_click)
        menu = QtWidgets.QMenu()

        # 创建显示器对应壁纸项
        self._monitors = get_monitors()
        self.__levels = self.__db_helper.get_model_data_list('level')
        self.create_monitor_menu(menu)

        # 壁纸切换方式
        self.__change_type_actions = list()
        self.create_change_type_menu(menu)

        switch_next = QtWidgets.QAction("切换下一张", self)
        switch_next.triggered.connect(self.__change_background)
        menu.addAction(switch_next)
        # 加载默认参数
        type_value = self.__config_helper.get_config_key(
            self.__config_section_background, self.__config_key_change_type,
            ChangeType.Order.value)
        self.__change_type = ChangeType(int(type_value))
        self.__update_change_type_action(self.__change_type)
        offset = self.__config_helper.get_config_key(
            self.__config_section_background,
            self.__config_key_last_order_image_offset, 0)
        self.__last_order_image_offset = int(offset)

        menu.addSeparator()
        setting = QtWidgets.QAction("设置", self)
        setting.triggered.connect(self.show)
        menu.addAction(setting)
        close = QtWidgets.QAction("退出", self)
        close.triggered.connect(self.close)
        menu.addAction(close)
        self.__tray.setContextMenu(menu)
        self.__tray.show()

        threading.Thread(target=self.__change_windows_background_timely,
                         daemon=True).start()
Esempio n. 37
0
def monitor():
    for m in get_monitors():
        return str(m)
Esempio n. 38
0
import cv2
import numpy as np
import serial
import time
from typing import Dict

import mss
from PIL import Image
from screeninfo import get_monitors

print(f"Welcome to AnimeColor!")

curr_monitor = get_monitors()[0]
# Settings
s_width = curr_monitor.width
s_height = curr_monitor.height
print(f"Detected monitor size {s_width}x{s_height}")
scalingFactor = 0.1
print(f"Using scaling factor {scalingFactor}")
show = False
interval = 100 # milliseconds
print(f"Color check interval {interval}")

# begin
for serial_port_n in range(3, 20):
    serial_port = f"COM{serial_port_n}"
    # print(f"Trying to connect to Arduino on port {serial_port}")
    try:
        arduino = serial.Serial(serial_port, 9600, timeout=0)
        print(f"Connected to Arduino on port {serial_port}")
        break
Esempio n. 39
0
    def flow(self):
        screen_id = 1
        is_color = False
        # get the size of the screen
        screen = screeninfo.get_monitors()[screen_id]
        width, height = screen.width, screen.height
        window_name = 'MonkeyView'
        cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)
        cv2.moveWindow(window_name, screen.x - 1, screen.y - 1)
        cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN,
                              cv2.WINDOW_FULLSCREEN)

        # 创建延迟队列
        q = queue.Queue(maxsize=int(self.delay / 20))  # 队列长度等于延迟除以每一帧的计算时间

        self.monkeySkin = cv2.imread(
            "D:\\Intern\\cvImgPy\\pics\\nbk.png")  # 猴子毛发提取
        # self.monkeySkin = cv2.medianBlur(self.monkeySkin, 21)  # 去噪 消除边缘

        self.woodPic = cv2.imread(
            "D:\\Intern\\cvImgPy\\pics\\wood.png")  # 木头图片
        self.cap = cv2.VideoCapture(0)  # 从摄像头读取
        # self.cap = cv2.VideoCapture('D:\\Intern\\cvImgPy\\pics\\real.MOV')  # 选择摄像头,把视频读取删除

        while self.cap.isOpened():
            starttime = datetime.datetime.now()  # 开始计算
            ret, self.frame = self.cap.read()
            if isinstance(
                    self.frame,
                    np.ndarray):  # 因为从某一帧开始,读取的视频就不是ndarray格式的了,导致报错,所以加一个判断

                # 剪切图像
                self.frame = self.frame[0:293, 0:640]
                self.frame = self.frame[:, ::-1]  # 左右翻转镜像

                # 中值去噪,真去噪
                # self.frame = cv2.medianBlur(self.frame, 5)

                # 刷新背景
                self.canvas = np.zeros((height, width, 3), dtype=np.float32)
                cv2.rectangle(self.canvas, (self.leftMg, self.upMg),
                              (self.leftMg + self.bkW, self.upMg + self.bkH),
                              (1, 1, 1), -1)

                # 判断角度有无改变
                if self.changed == 1:
                    self.radian = 2 * math.pi * self.theta / 360
                    self.sin = math.sin(self.radian)
                    self.cos = math.cos(self.radian)
                    self.tan = math.tan(self.radian)
                    self.changed = 0

                # 尺寸变换
                self.frame = cv2.resize(
                    self.frame,
                    (int(self.bkW * self.scal_x), int(self.bkH * self.scal_y)),
                    interpolation=cv2.INTER_LINEAR)
                # 清晰度变换,均值去噪
                self.frame = cv2.blur(self.frame, (self.dim, self.dim))

                # 开始修补
                self.center = [0.5 * self.frame.shape[1],
                               self.frame.shape[0]]  # 先x后y, mask坐标系

                # 制作掩膜
                self.makeMask(self.fColor)

                # 如果没有手,也空白
                # 开始按照手和木头进行分类
                # 显示空白
                if self.wood == 2 or len(
                        np.where(self.mask[270] != 0)[0]) < 20:
                    if self.showRed == 1:
                        cv2.circle(
                            self.canvas,
                            (self.leftMg + self.redX, self.upMg + self.redY),
                            10, (0, 0, 255), -1)

                    if self.showBlue == 1:
                        cv2.circle(
                            self.canvas,
                            (self.leftMg + self.blueX, self.upMg + self.blueY),
                            15, (255, 0, 0), -1)

                if self.wood == 3:
                    cv2.rectangle(
                        self.canvas, (self.leftMg, self.upMg),
                        (self.leftMg + self.bkW, self.upMg + self.bkH),
                        (0, 0, 0), -1)

                # 显示手
                elif self.wood == 0:
                    # start = int(np.where(self.mask[self.mask.shape[0] - 1] != 0)[0][0])
                    # end = int(np.where(self.mask[self.mask.shape[0] - 1] != 0)[0][-1])
                    #
                    # # 拟合直线
                    # self.linefit()
                    #
                    # self.monkeySkin = self.monkeySkin[0:self.frame.shape[0], 0:self.frame.shape[1]]
                    #
                    # # 分旋转方向,计算直线和交点
                    # if self.theta > 0:
                    #     # 根据手的左中右位置,修补区域不同
                    #     if start > 0.5 * self.bkW:
                    #         # 没有加斜率不存在的判断,考虑到拟合时有20个点
                    #         # 求交点
                    #         if self.left[0] == self.left[0]:  # 判断前面算的斜率是不是NaN
                    #             left_point = self.intersection(self.left)
                    #         else:
                    #             left_point = [start, self.center[1] + int(start * self.tan)]
                    #
                    #         if self.right[0] == self.right[0]:
                    #             right_point = self.intersection(self.right)
                    #         else:
                    #             right_point = [end, self.center[1] + int(end * self.tan)]
                    #
                    #         # 求交点旋转后的位置
                    #         lp_rot = self.point_rot(left_point)
                    #         rp_rot = self.point_rot(right_point)
                    #         # 会出问题
                    #         # if rp_rot[0] < 0:
                    #         #     print(right_x)
                    #         #     print(right)
                    #
                    #         # 绘制四边形
                    #         start_point = [self.center[0] + int((start - self.center[0]) * self.cos), self.center[1] - int((start - self.center[0]) * self.sin)]  # 先x后y
                    #         end_point = [self.center[0] + int((end - self.center[0]) * self.cos), self.center[1] - int((end - self.center[0]) * self.sin)]
                    #
                    #         # 错误情况处理
                    #         if 'previous_1' in locals().keys():
                    #             if rp_rot[0] < 0 or abs(rp_rot[0] - self.previous_1[0]) > 80:  # 根据猴子手的速度不同进行调节,这地方要有调参的
                    #                 rp_rot = self.previous_1
                    #             else:
                    #                 self.previous_1 = rp_rot
                    #         else:
                    #             self.previous_1 = rp_rot
                    #
                    #         box = np.array([[start_point, lp_rot, rp_rot, end_point]], dtype = np.int32)
                    #
                    #         self.makeUpMky(box)
                    #
                    #
                    #     elif start <= 0.5 * self.bkW and end >= 0.5 * self.bkW:
                    #
                    #         if self.right[0] == self.right[0]:
                    #             right_point = self.intersection(self.right)
                    #         else:
                    #             right_point = [end, self.center[1] + int(end * self.tan)]
                    #
                    #         rp_rot = self.point_rot(right_point)
                    #
                    #         start_point = self.center
                    #         end_point = [self.center[0] + int((end - self.center[0]) * self.cos), self.center[1] - int((end - self.center[0]) * self.sin)]
                    #
                    #         # 错误情况处理,暂时没什么要处理的,先留着
                    #         if 'previous_2' in locals().keys():
                    #             if rp_rot[0] < 0:
                    #                 rp_rot = self.previous_2
                    #             else:
                    #                 self.previous_2 = rp_rot
                    #         else:
                    #             self.previous_2 = rp_rot
                    #
                    #         box = np.array([[start_point, rp_rot, end_point]], dtype=np.int32)
                    #         # 画三角形
                    #         self.makeUpMky(box)
                    #
                    # if self.theta < 0:
                    #     if end < 0.5 * self.bkW:
                    #
                    #         if self.left[0] == self.left[0]:  # 判断前面算的斜率是不是NaN
                    #             left_point = self.intersection(self.left)
                    #         else:
                    #             left_point = [start, self.center[1] + int(start * self.tan)]
                    #
                    #         if self.right[0] == self.right[0]:
                    #             right_point = self.intersection(self.right)
                    #         else:
                    #             right_point = [end, self.center[1] + int(end * self.tan)]
                    #
                    #         lp_rot = self.point_rot(left_point)
                    #         rp_rot = self.point_rot(right_point)
                    #
                    #         start_point = [self.center[0] + int((start - self.center[0]) * self.cos), self.center[1] - int((start - self.center[0]) * self.sin)]  # 先x后y
                    #         end_point = [self.center[0] + int((end - self.center[0]) * self.cos), self.center[1] - int((end - self.center[0]) * self.sin)]
                    #
                    #         # 错误情况处理
                    #         if 'previous_3' in locals().keys():
                    #             if rp_rot[0] < 0 or abs(rp_rot[0] - self.previous_3[0]) > 80:  # 根据猴子手的速度不同进行调节,这地方要有调参的
                    #                 rp_rot = self.previous_3
                    #             else:
                    #                 self.previous_3 = rp_rot
                    #         else:
                    #             self.previous_3 = rp_rot
                    #
                    #         box = np.array([[start_point, lp_rot, rp_rot, end_point]], dtype=np.int32)
                    #         self.makeUpMky(box)
                    #
                    #     elif start < 0.5 * self.bkW and end > 0.5 * self.bkW:
                    #         if self.left[0] == self.left[0]:  # 判断前面算的斜率是不是NaN
                    #             left_point = self.intersection(self.left)
                    #         else:
                    #             left_point = [start, self.center[1] + int(start * self.tan)]
                    #
                    #         lp_rot = self.point_rot(left_point)
                    #
                    #         start_point = self.center
                    #         end_point = [self.center[0] + int((start - self.center[0]) * self.cos), self.center[1] - int((start - self.center[0]) * self.sin)]
                    #
                    #         # 错误情况处理,暂时没什么要处理的,先留着
                    #         if 'previous_4' in locals().keys():
                    #             if lp_rot[0] < 0:
                    #                 lp_rot = self.previous_4
                    #             else:
                    #                 self.previous_4 = lp_rot
                    #         else:
                    #             self.previous_4 = lp_rot
                    #
                    #         box = np.array([[start_point, lp_rot, end_point]], dtype=np.int32)
                    #         # 画三角形
                    #         self.makeUpMky(box)
                    # # 到此修补完毕

                    # 旋转变换
                    self.handRotate(self.theta)

                    self.copyTo()

                    if self.showRed == 1:
                        cv2.circle(
                            self.canvas,
                            (self.leftMg + self.redX, self.upMg + self.redY),
                            10, (0, 0, 255), -1)

                    if self.showBlue == 1:
                        cv2.circle(
                            self.canvas,
                            (self.leftMg + self.blueX, self.upMg + self.blueY),
                            15, (255, 0, 0), -1)

                # 显示木头
                elif self.wood == 1:
                    # start = int(np.where(self.mask[self.mask.shape[0] - 1] != 0)[0][0])
                    # end = int(np.where(self.mask[self.mask.shape[0] - 1] != 0)[0][-1])
                    #
                    # # 拟合直线
                    # self.linefit()
                    #
                    # self.woodPic = self.woodPic[0:self.frame.shape[0], 0:self.frame.shape[1]]
                    #
                    # # 分旋转方向,计算直线和交点
                    # if self.theta > 0:
                    #     # 根据手的左中右位置,修补区域不同
                    #     if start > 0.5 * self.bkW:
                    #         # 没有加斜率不存在的判断,考虑到拟合时有20个点
                    #         # 求交点
                    #         if self.left[0] == self.left[0]:  # 判断前面算的斜率是不是NaN
                    #             left_point = self.intersection(self.left)
                    #         else:
                    #             left_point = [start, self.center[1] + int(start * self.tan)]
                    #
                    #         if self.right[0] == self.right[0]:
                    #             right_point = self.intersection(self.right)
                    #         else:
                    #             right_point = [end, self.center[1] + int(end * self.tan)]
                    #
                    #         # 求交点旋转后的位置
                    #         lp_rot = self.point_rot(left_point)
                    #         rp_rot = self.point_rot(right_point)
                    #         # 会出问题
                    #         # if rp_rot[0] < 0:
                    #         #     print(right_x)
                    #         #     print(right)
                    #
                    #         # 绘制四边形
                    #         start_point = [self.center[0] + int((start - self.center[0]) * self.cos),
                    #                        self.center[1] - int((start - self.center[0]) * self.sin)]  # 先x后y
                    #         end_point = [self.center[0] + int((end - self.center[0]) * self.cos),
                    #                      self.center[1] - int((end - self.center[0]) * self.sin)]
                    #
                    #         # 错误情况处理
                    #         if 'previous_1' in locals().keys():
                    #             if rp_rot[0] < 0 or abs(rp_rot[0] - self.previous_1[0]) > 80:  # 根据猴子手的速度不同进行调节,这地方要有调参的
                    #                 rp_rot = self.previous_1
                    #             else:
                    #                 self.previous_1 = rp_rot
                    #         else:
                    #             self.previous_1 = rp_rot
                    #
                    #         box = np.array([[start_point, lp_rot, rp_rot, end_point]], dtype=np.int32)
                    #
                    #         self.makeUpMky(box)
                    #
                    #
                    #     elif start <= 0.5 * self.bkW and end >= 0.5 * self.bkW:
                    #
                    #         if self.right[0] == self.right[0]:
                    #             right_point = self.intersection(self.right)
                    #         else:
                    #             right_point = [end, self.center[1] + int(end * self.tan)]
                    #
                    #         rp_rot = self.point_rot(right_point)
                    #
                    #         start_point = self.center
                    #         end_point = [self.center[0] + int((end - self.center[0]) * self.cos),
                    #                      self.center[1] - int((end - self.center[0]) * self.sin)]
                    #
                    #         # 错误情况处理,暂时没什么要处理的,先留着
                    #         if 'previous_2' in locals().keys():
                    #             if rp_rot[0] < 0:
                    #                 rp_rot = self.previous_2
                    #             else:
                    #                 self.previous_2 = rp_rot
                    #         else:
                    #             self.previous_2 = rp_rot
                    #
                    #         box = np.array([[start_point, rp_rot, end_point]], dtype=np.int32)
                    #         # 画三角形
                    #         self.makeUpMky(box)
                    #
                    # if self.theta < 0:
                    #     if end < 0.5 * self.bkW:
                    #
                    #         if self.left[0] == self.left[0]:  # 判断前面算的斜率是不是NaN
                    #             left_point = self.intersection(self.left)
                    #         else:
                    #             left_point = [start, self.center[1] + int(start * self.tan)]
                    #
                    #         if self.right[0] == self.right[0]:
                    #             right_point = self.intersection(self.right)
                    #         else:
                    #             right_point = [end, self.center[1] + int(end * self.tan)]
                    #
                    #         lp_rot = self.point_rot(left_point)
                    #         rp_rot = self.point_rot(right_point)
                    #
                    #         start_point = [self.center[0] + int((start - self.center[0]) * self.cos),
                    #                        self.center[1] - int((start - self.center[0]) * self.sin)]  # 先x后y
                    #         end_point = [self.center[0] + int((end - self.center[0]) * self.cos),
                    #                      self.center[1] - int((end - self.center[0]) * self.sin)]
                    #
                    #         # 错误情况处理
                    #         if 'previous_3' in locals().keys():
                    #             if rp_rot[0] < 0 or abs(rp_rot[0] - self.previous_3[0]) > 80:  # 根据猴子手的速度不同进行调节,这地方要有调参的
                    #                 rp_rot = self.previous_3
                    #             else:
                    #                 self.previous_3 = rp_rot
                    #         else:
                    #             self.previous_3 = rp_rot
                    #
                    #         box = np.array([[start_point, lp_rot, rp_rot, end_point]], dtype=np.int32)
                    #         self.makeUpMky(box)
                    #
                    #     elif start < 0.5 * self.bkW and end > 0.5 * self.bkW:
                    #         if self.left[0] == self.left[0]:  # 判断前面算的斜率是不是NaN
                    #             left_point = self.intersection(self.left)
                    #         else:
                    #             left_point = [start, self.center[1] + int(start * self.tan)]
                    #
                    #         lp_rot = self.point_rot(left_point)
                    #
                    #         start_point = self.center
                    #         end_point = [self.center[0] + int((start - self.center[0]) * self.cos),
                    #                      self.center[1] - int((start - self.center[0]) * self.sin)]
                    #
                    #         # 错误情况处理,暂时没什么要处理的,先留着
                    #         if 'previous_4' in locals().keys():
                    #             if lp_rot[0] < 0:
                    #                 lp_rot = self.previous_4
                    #             else:
                    #                 self.previous_4 = lp_rot
                    #         else:
                    #             self.previous_4 = lp_rot
                    #
                    #         box = np.array([[start_point, lp_rot, end_point]], dtype=np.int32)
                    #         # 画三角形
                    #         self.makeUpMky(box)
                    # # 到此修补完毕

                    # 旋转变换
                    self.handRotate(self.theta)

                    self.copyTo()

                    if self.showRed == 1:
                        cv2.circle(
                            self.canvas,
                            (self.leftMg + self.redX, self.upMg + self.redY),
                            10, (0, 0, 255), -1)
                    if self.showBlue == 1:
                        cv2.circle(self.canvas, (self.blueX, self.blueY), 15,
                                   (255, 0, 0), -1)

                # 延迟,队列真美妙
                if self.delay != 0:
                    if q.full():
                        cv2.imshow(window_name, q.get())
                        q.put(self.canvas)
                    else:
                        q.put(self.canvas)
                else:
                    cv2.imshow(window_name, self.canvas)

                # cv2.imshow(window_name, self.canvas)
                # interval = datetime.datetime.now() - starttime
                # print(interval)
            else:
                break
            if cv2.waitKey(1) & 0xFF == ord('q'):  # 按q键退出
                break

        self.cap.release()
        cv2.destroyAllWindows()
Esempio n. 40
0
conf_parser = ap.ArgumentParser(description='Delete all right frame files in folder based on which left frame files remain.')

conf_parser.add_argument("-f", "--folder", help="Folder to work in", 
                    required=False, default= ["./"])

if __name__ == "__main__":
    args = conf_parser.parse_args()
    files = [f for f in os.listdir(args.folder) if osp.isfile(osp.join(args.folder,f)) and f.endswith(".png")]
    files.sort()
    
    rfiles = [f for f in files if "r_" in f]
    lfiles = [f for f in files if "l_" in f]
    rfiles.sort()
    lfiles.sort()
    
    monitors = scr.get_monitors()
    main_monitor = monitors[0]
    screen_height = main_monitor.height
    header_height = 100
    resized_height = 250
    padding = 10
    
    #assume frames of equal dimensions for right & left
    sample_frame = cv2.imread(osp.join(args.folder,lfiles[0]))
    resized_width = int(sample_frame.shape[1] * resized_height / sample_frame.shape[0])
    new_size = (resized_width,resized_height)
    step = int((screen_height - header_height - padding) / (resized_height+padding))
    pane_width = 2*resized_width + (3*padding)
    pane_height = screen_height - header_height
    pane_dims = (pane_height,pane_width,3)
    x_left = padding
Esempio n. 41
0
        map_table.add_row(['DOWNLOAD MORE'])
        print(map_table)
        select = str(input('          Select map: '))
        if select == 'DOWNLOAD MORE':
            map = download()
        else:
            map = select
        pixel_width = pixel_width(config, map)
        restore_session = False
    else:
        sys.exit(0)
else:
    map = download()
    pixel_width = pixel_width(config, map)
    restore_session = False

for m in get_monitors():  # resets Windows DPI scaling
    print('', end='')

root = Tk()
root.tk.call('tk', 'scaling', 1.5)
app = Window(root,
             'maps/' + map,
             pixel_width,
             restore_session,
             subwindow=False)

root.attributes('-fullscreen', True)
root.wm_title("Lunar Heightmap Calculator")
root.mainloop()
Esempio n. 42
0
import math
from screeninfo import get_monitors

# это можно настроить по желанию

lines = 200  # Количество лучей (качество картинки)
is_minimap = False  # нужно ли рисовать миникарту
max_unit = 30  # максимальное количество мобов

# то что ниже трогать нельзя!!!!!

FPS = 60  # фпс

width = get_monitors()[0].width  # получение разрешения экрана
height = get_monitors()[0].height

# size = 32, 32  # размер карты
# half_size = size[0] // 2, size[1] // 2  # центр карты и начальнаяпозиция игрока
rect_size2d = 60  # размер 2д прямоугольника на карте

fow = 60  # область видимости
line_step = fow / lines / 50  # угол между лучами
line_to_px = width / lines  # ширина линии в 3д

# всякие нужные цвета
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
gray = (128, 128, 128)
dk_gray = (16, 16, 16)
black = (0, 0, 0)
Esempio n. 43
0
    def __init__(self, pluginPath, corePath, configFile):
        self.pluginPath = pluginPath
        self.corePath = corePath
        self.workingDir = sys.path[0]
        self.configFile = self.corePath + '\\' + configFile
        self.PGconfigFile = self.workingDir + '\\' + 'PG_config.ini'
        self.PGconfigFileCore = self.corePath + '\\' + 'PG_config.ini'
        self.PG_expanded = False
        self.current_y_pxpos_elem = 0
        self.param_dict = {}
        self.section_EC_stat = {}
        self.KST = key_stroke_timer.key_stroke_timer(self.configFile)
        self.MIN_SIZE_W = 20
        self.black_list = ['collapse', 'create', 'hideSection', 'show', 'filterStrategy', 'offsetType']

        self.GOC = guard.guard_of_changes(self)  # init observer thread
        self.GOC.start()  # start observer thread

        wx.Dialog.__init__(self, None, title='MW Parameter guard', size=UI.WMAIN['size'],
                           style=wx.SYSTEM_MENU | # wx.CAPTION |  # ~wx.CLOSE_BOX |
                                 wx.TAB_TRAVERSAL | wx.STAY_ON_TOP | wx.RESIZE_BORDER)  # | wx.TRANSPARENT_WINDOW)

        self.SetMinSize((1, 1))

        PG_XY = ini_worker.get_param_from_ini(self.PGconfigFileCore, 'UISETTINGS', 'lastWindowPosition')
        PG_XY = PG_XY.strip()[1:-1].split(',')
        PG_SIZE = ini_worker.get_param_from_ini(self.PGconfigFileCore, 'UISETTINGS', 'lastWindowSize')
        PG_SIZE = PG_SIZE.strip()[1:-1].split(',')


        self.MAIN_DISPLAY_SIZE = get_monitors()
        if len(self.MAIN_DISPLAY_SIZE) == 1:
            self.DISPLAY_SIZE = self.MAIN_DISPLAY_SIZE[0]
        else:
            self.DISPLAY_SIZE = self.MAIN_DISPLAY_SIZE[1]

        self.DISPLAY_SIZE = self.MAIN_DISPLAY_SIZE[0]

        #self.MoveXY(int(PG_XY[0]), int(PG_XY[1]))
        self.MoveXY(int(self.DISPLAY_SIZE.width)-10, 0)
        #self.SetSizeWH(int(PG_SIZE[0]), int(PG_SIZE[1]))
        self.SetSizeWH(int(PG_SIZE[0]), self.DISPLAY_SIZE.height)

        self.Bind(wx.EVT_SIZE, self.OnSize, self)
        # self.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
        # self.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)
        # self.Bind(wx.EVT_LEFT_DOWN, self.onLMouseDown)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.onMouseEvents)

        atable = wx.AcceleratorTable([(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_EXIT)])
        self.SetAcceleratorTable(atable)
        wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit)

        self.SetBackgroundColour(wx.Colour(UI.WCOLOR['BG'][0],
                                           UI.WCOLOR['BG'][1],
                                           UI.WCOLOR['BG'][2]))

        self.SetTransparent(220)
        self.Show()

        #fn = self.corePath + '\\bin\\images\\paramGuard.ico'
        #self.icon = wx.Icon(fn, wx.BITMAP_TYPE_ICO)
        #self.SetIcon(self.icon)

        self.section_list = ini_worker.get_sections_list_from_ini(self.configFile)  # list

        param_indentation = 10  # whitespace

        for section in self.section_list:

            self.section_EC_stat.update(
                {section: ini_worker.get_param_from_ini(self.configFile, section, 'collapse')})

            section_params = ini_worker.get_section_from_ini(self.configFile, section)
            for param, value in section_params.iteritems():
                if param == 'hideSection':
                    hideSection = value

            if not hideSection:

                self.param_dict[section] = {}

                font = wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.BOLD)

                headline = wx.StaticText(self,
                                         label=section,
                                         pos=(UI.THEADERSTART['pos'][0],
                                              UI.THEADERSTART['pos'][1] + self.current_y_pxpos_elem))

                headline.SetForegroundColour(UI.TCOLOR['FG'])  # set text color
                headline.SetFont(font)
                headline.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
                #headline.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)

                button = wx.Button(self,
                                   name=section,
                                   label="",
                                   pos=(UI.BEXPAND['pos'][0], self.current_y_pxpos_elem + 11),
                                   size=UI.BEXPAND['size'])

                button.Bind(wx.EVT_BUTTON, self.expandCollapse)
                button.SetBackgroundColour(UI.BCOLOR['BG'])  # set color
                button.SetToolTipString('Click to expand/collapse section')
                button.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
                #button.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)

                self.current_y_pxpos_elem += 20

                # params in sections (edit boxes)
                font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
                ui_elem_handler_dict = {}

                for param, value in section_params.iteritems():

                    if type(value) == str:
                        splitted_value = value.split(';')
                        if len(splitted_value) > 1:
                            if splitted_value[1].strip() == 'X':
                                self.black_list.append(param)

                    if param not in self.black_list:

                        text = wx.StaticText(self,
                                             label=param,
                                             pos=(UI.THEADERSTART['pos'][0] + param_indentation,
                                                  UI.THEADERSTART['pos'][1] + self.current_y_pxpos_elem))

                        text.SetForegroundColour(UI.PARAMCOLOR['FG'])  # set text color
                        text.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
                        #text.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)

                        editbox = (wx.TextCtrl(self,
                                               name=section + ' - ' + param,
                                               value=str(value),
                                               pos=(UI.EBOX['pos'][0], UI.THEADERSTART['pos'][1] + self.current_y_pxpos_elem),
                                               size=UI.EBOX['size'],
                                               style=wx.TE_PROCESS_ENTER))

                        editbox.SetForegroundColour(UI.ECOLOR2['FG'])  # set color
                        editbox.SetBackgroundColour(UI.ECOLOR2['BG'])  # set color

                        editbox.Bind(wx.EVT_TEXT, self.EvtText)
                        editbox.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
                        #editbox.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)


                        elem_dict = {param: [{'ebox': [editbox, value]},
                                             {'headline': headline},
                                             {'text': text},
                                             {'button': button}]}

                        ui_elem_handler_dict.update(elem_dict)

                        self.current_y_pxpos_elem += 20

                    self.param_dict[section].update(ui_elem_handler_dict)

        self.expandCollapse(None, refresh=True)
        self.refresh_UI()
        self.KST.start()
Esempio n. 44
0
    def setting_transform(self, input_fname):
        # 映像開く
        video = cv2.VideoCapture(input_fname)
        # 開けた確認
        if not video.isOpened():
            print("video open error")
            return

        # 映像情報
        video_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
        video_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

        # モニター情報
        monitor_width = get_monitors()[0].width
        monitor_height = get_monitors()[0].height

        # 座標関係
        # 元の大きさでそのまま
        original_up_left = [0, 0]
        original_up_right = [video_width, 0]
        original_under_left = [0, video_height]
        original_under_right = [video_width, video_height]
        # np化
        original_pos = np.float32([
            original_up_left,
            original_up_right,
            original_under_left,
            original_under_right,
        ])
        # 変換後の座標
        update_up_left = [0, 0]
        update_up_right = [monitor_width, 0]
        update_under_left = [0, monitor_height]
        update_under_right = [monitor_width, monitor_height]
        update_array = [
            update_up_left, update_up_right, update_under_left,
            update_under_right
        ]

        # opencv表示
        winname = "transform"
        cv2.namedWindow(winname, cv2.WINDOW_NORMAL)
        cv2.setWindowProperty(winname, cv2.WND_PROP_FULLSCREEN,
                              cv2.WINDOW_FULLSCREEN)

        # 一枚ずつ表示
        while True:
            # 画像
            ret, img = video.read()
            # 読み込みできんかったら映像の最初に移動
            if not ret:
                video.set(cv2.CAP_PROP_POS_FRAMES, 0)
                continue

            # キー入力
            key = cv2.waitKey(1) & 0xff
            # キー入力結果
            if key == 13:
                # エンターキーで終了
                break
            elif key == ord('1'):
                # 1なら左上の位置をマウスの位置に合わせる
                update_array[0] = pyautogui.position()
            elif key == ord('2'):
                # 2なら右上の位置をマウスの位置に合わせる
                update_array[1] = pyautogui.position()
            elif key == ord('3'):
                # 3なら左下の位置をマウスの位置に合わせる
                update_array[2] = pyautogui.position()
            elif key == ord('4'):
                # 4なら右下の位置をマウスの位置に合わせる
                update_array[3] = pyautogui.position()

            # 変形後の座標np化
            update_pos = np.float32(update_array)
            # 変換行列作成
            matrix = cv2.getPerspectiveTransform(original_pos, update_pos)
            # 変換
            update_img = cv2.warpPerspective(img, matrix,
                                             (monitor_width, monitor_height))

            # 表示
            self.show_img_fullscreen(winname, update_img)

        # 閉じ
        video.release()
        # 画面と次
        cv2.destroyAllWindows()

        # 大きさとか座標の辞書か
        result = {
            "fname": input_fname,
            "monitor_width": monitor_width,
            "monitor_height": monitor_height,
            "video_width": video_width,
            "video_height": video_height,
            "update_up_left": update_array[0],
            "update_up_right": update_array[1],
            "update_under_left": update_array[2],
            "update_under_right": update_array[3]
        }

        return result
Esempio n. 45
0
                            "exodus",
                            "fields",
                            "hunting-season",
                            "lost-beyond",
                            "entresueno",
                            ]]

dI_list = []
for key, value in wallpaper_links.items():
    for i, name in enumerate(value[1]):
        url = urllib.parse.urljoin(value[0], name)
        content = ReqContent(url).get()
        htmlElements = content.find_class("wallpaper-button")
        dI_list.append([])
        for htmlElement in htmlElements:
            dI_list[-1].append(DownloadImage(htmlElement))
        print(i, "/", len(value[1]))

img_dir = "/home/kwon-young/Pictures/wallpapers"
monitor_res = get_monitors()[0]
for i, dI_img in enumerate(dI_list):
    monitor_list = [str2monitor(x._res) for x in dI_img]
    goalIndex = [i for i, x in enumerate(monitor_list) if x.width == monitor_res.width and x.height == monitor_res.height]
    if len(goalIndex) == 0:
        print("Warning ! res not found for " + dI_img[0]._downloadName)
    goalIndex = goalIndex[0]
    with open(os.path.join(img_dir, dI_img[goalIndex]._downloadName), "wb") as f:
        response = requests.get(dI_img[goalIndex]._downloadUrl)
        f.write(response.content)
    print(i, "/", len(dI_list))