def rebuild_hit_chain(self, current_widget, current_matrix=None): # If there is a matrix for the widget concatenate it. if current_widget.matrix is not None: matrix_within_scene = Matrix(current_widget.matrix) matrix_within_scene.post_cat(current_matrix) else: matrix_within_scene = Matrix(current_matrix) # Add to list and recurse for children based on response. response = current_widget.hit() if response == HITCHAIN_HIT: self.hittable_elements.append( (current_widget, matrix_within_scene)) elif response == HITCHAIN_DELEGATE: for w in current_widget: self.rebuild_hit_chain(w, matrix_within_scene) elif response == HITCHAIN_HIT_AND_DELEGATE: self.hittable_elements.append( (current_widget, matrix_within_scene)) for w in current_widget: self.rebuild_hit_chain(w, matrix_within_scene) elif response == HITCHAIN_DELEGATE_AND_HIT: for w in current_widget: self.rebuild_hit_chain(w, matrix_within_scene) self.hittable_elements.append( (current_widget, matrix_within_scene))
def __init__(self, scene, left=None, top=None, right=None, bottom=None, all=False): list.__init__(self) self.matrix = Matrix() self.scene = scene self.parent = None self.properties = ORIENTATION_RELATIVE if all: # contains all points self.left = -float('inf') self.top = -float('inf') self.right = float('inf') self.bottom = float('inf') else: # contains no points self.left = float('inf') self.top = float('inf') self.right = -float('inf') self.bottom = -float('inf') if left is not None: self.left = left if right is not None: self.right = right if top is not None: self.top = top if bottom is not None: self.bottom = bottom
def __init__(self): Module.__init__(self) self.hittable_elements = list() self.hit_chain = list() self.widget_root = SceneSpaceWidget(self) self.matrix_root = Matrix() self.process = self.animate_tick self.interval = 1.0 / 60.0 # 60fps self.last_position = None self.time = None self.distance = None
kernel.load(os.path.realpath(args.input.name)) if args.path is not None: # Force the inclusion of the path. from svgelements import Path try: path = Path(args.path) path.stroke = Color('blue') kernel.elements.add_elem(path) except Exception: print("SVG Path Exception to: %s" % ' '.join(sys.argv)) if args.transform: # Transform any data loaded data from svgelements import Matrix m = Matrix(args.transform) for e in kernel.elements.elems(): e *= m try: e.modified() except AttributeError: pass if args.set is not None: # Set the variables requested here. for v in args.set: attr = v[0] value = v[1] if hasattr(device, attr): v = getattr(device, attr) if isinstance(v, bool):
def wizard_image(svg_image, operations): image = svg_image.image matrix = Matrix(svg_image.transform) step = None mask = None from PIL import Image, ImageOps, ImageFilter, ImageEnhance for op in operations: name = op['name'] if name == 'crop': try: if op['enable'] and op['bounds'] is not None: crop = op['bounds'] left = int(crop[0]) upper = int(crop[1]) right = int(crop[2]) lower = int(crop[3]) image = image.crop((left, upper, right, lower)) except KeyError: pass if name == 'resample': try: if op['enable']: image, matrix = RasterScripts.actualize( image, matrix, step_level=op['step']) step = op['step'] except KeyError: pass if name == 'grayscale': try: if op['enable']: try: r = op['red'] * 0.299 g = op['green'] * 0.587 b = op['blue'] * 0.114 v = op['lightness'] c = r + g + b try: c /= v r = r / c g = g / c b = b / c except ZeroDivisionError: pass m = [r, g, b, 1.0] if image.mode != "L": if image.mode == "P" or image.mode == '1': image = image.convert('RGBA') if op['invert']: color = 0, 0, 0 c8 = 0 else: color = 255, 255, 255 c8 = 255 if image.mode == 'RGBA': background = Image.new( 'RGB', image.size, color) background.paste( image, mask=image.getchannel('A')) image = background image = image.convert("L", matrix=m) def mask_filter(e): if e == c8: return 0 else: return 255 mask = image.point( mask_filter ) # Makes a mask out of Alpha or pure mask color. if op['invert']: image = ImageOps.invert(image) except (KeyError, OSError): pass except KeyError: pass if name == 'edge_enhance': try: if op['enable']: if image.mode == 'P': image = image.convert('L') image = image.filter(filter=ImageFilter.EDGE_ENHANCE) except KeyError: pass if name == 'auto_contrast': try: if op['enable']: if image.mode != 'P': image = image.convert('L') image = ImageOps.autocontrast(image, cutoff=op['cutoff']) except KeyError: pass if name == 'tone': try: if op['enable'] and op['values'] is not None: if image.mode == 'L': image = image.convert('P') tone_values = op['values'] if op['type'] == 'spline': spline = RasterScripts.spline(tone_values) else: tone_values = [ q for q in tone_values if q is not None ] spline = RasterScripts.line(tone_values) if len(spline) < 256: spline.extend([255] * (256 - len(spline))) if len(spline) > 256: spline = spline[:256] image = image.point(spline) if image.mode != 'L': image = image.convert('L') except KeyError: pass if name == 'contrast': try: if op['enable']: if op['contrast'] is not None and op[ 'brightness'] is not None: contrast = ImageEnhance.Contrast(image) c = (op['contrast'] + 128.0) / 128.0 image = contrast.enhance(c) brightness = ImageEnhance.Brightness(image) b = (op['brightness'] + 128.0) / 128.0 image = brightness.enhance(b) except KeyError: pass if name == 'gamma': try: if op['enable'] and op['factor'] is not None: if image.mode == 'L': gamma_factor = float(op['factor']) def crimp(px): px = int(round(px)) if px < 0: return 0 if px > 255: return 255 return px if gamma_factor == 0: gamma_lut = [0] * 256 else: gamma_lut = [ crimp( pow(i / 255, (1.0 / gamma_factor)) * 255) for i in range(256) ] image = image.point(gamma_lut) if image.mode != 'L': image = image.convert('L') except KeyError: pass if name == 'unsharp_mask': try: if op['enable'] and \ op['percent'] is not None and \ op['radius'] is not None and \ op['threshold'] is not None: unsharp = ImageFilter.UnsharpMask( radius=op['radius'], percent=op['percent'], threshold=op['threshold']) image = image.filter(unsharp) except (KeyError, ValueError): # Value error if wrong type of image. pass if name == 'dither': try: if op['enable'] and op['type'] is not None: if mask is not None: background = Image.new(image.mode, image.size, 'white') background.paste(image, mask=mask) image = background # Mask exists use it to remove any pixels that were pure reject. if image.mode == 'RGBA': pixel_data = image.load() width, height = image.size for y in range(height): for x in range(width): if pixel_data[x, y][3] == 0: pixel_data[x, y] = (255, 255, 255, 255) image = image.convert("1") except KeyError: pass if name == 'halftone': try: if op['enable']: image = RasterScripts.halftone( image, sample=op['sample'], angle=op['angle'], oversample=op['oversample'], black=op['black']) except KeyError: pass return image, matrix, step
def __init__(self, *args, **kwds): # begin wxGlade: CameraInterface.__init__ kwds["style"] = kwds.get( "style", 0 ) | wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT | wx.TAB_TRAVERSAL wx.Frame.__init__(self, *args, **kwds) Module.__init__(self) self.SetSize((608, 549)) self.CameraInterface_menubar = wx.MenuBar() wxglade_tmp_menu = wx.Menu() item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Reset Perspective"), "") self.Bind(wx.EVT_MENU, self.reset_perspective, id=item.GetId()) item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Reset Fisheye"), "") self.Bind(wx.EVT_MENU, self.reset_fisheye, id=item.GetId()) wxglade_tmp_menu.AppendSeparator() item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Set IP Camera 1"), "", wx.ITEM_RADIO) self.camera_ip_menu1 = item self.Bind(wx.EVT_MENU, lambda e: self.swap_camera(-1), id=item.GetId()) item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Set IP Camera 2"), "", wx.ITEM_RADIO) self.camera_ip_menu2 = item self.Bind(wx.EVT_MENU, lambda e: self.swap_camera(-2), id=item.GetId()) item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Set IP Camera 3"), "", wx.ITEM_RADIO) self.camera_ip_menu3 = item self.Bind(wx.EVT_MENU, lambda e: self.swap_camera(-3), id=item.GetId()) item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Set Camera 0"), "", wx.ITEM_RADIO) self.camera_0_menu = item self.Bind(wx.EVT_MENU, lambda e: self.swap_camera(0), id=item.GetId()) item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Set Camera 1"), "", wx.ITEM_RADIO) self.camera_1_menu = item self.Bind(wx.EVT_MENU, lambda e: self.swap_camera(1), id=item.GetId()) item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Set Camera 2"), "", wx.ITEM_RADIO) self.camera_2_menu = item self.Bind(wx.EVT_MENU, lambda e: self.swap_camera(2), id=item.GetId()) item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Set Camera 3"), "", wx.ITEM_RADIO) self.camera_3_menu = item self.Bind(wx.EVT_MENU, lambda e: self.swap_camera(3), id=item.GetId()) item = wxglade_tmp_menu.Append(wx.ID_ANY, _("Set Camera 4"), "", wx.ITEM_RADIO) self.camera_4_menu = item self.Bind(wx.EVT_MENU, lambda e: self.swap_camera(4), id=item.GetId()) self.CameraInterface_menubar.Append(wxglade_tmp_menu, _("Camera")) self.SetMenuBar(self.CameraInterface_menubar) # Menu Bar self.button_update = wx.BitmapButton(self, wx.ID_ANY, icons8_camera_50.GetBitmap()) self.button_export = wx.BitmapButton( self, wx.ID_ANY, icons8_picture_in_picture_alternative_50.GetBitmap()) self.check_fisheye = wx.CheckBox(self, wx.ID_ANY, _("Correct Fisheye")) self.check_perspective = wx.CheckBox(self, wx.ID_ANY, _("Correct Perspective")) self.slider_fps = wx.Slider(self, wx.ID_ANY, 1, 0, 24, style=wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS) self.button_detect = wx.BitmapButton(self, wx.ID_ANY, icons8_detective_50.GetBitmap()) self.display_camera = wx.Panel(self, wx.ID_ANY) self.__set_properties() self.__do_layout() self.capture = None self.image_width = -1 self.image_height = -1 self._Buffer = None self.frame_bitmap = None self.fisheye_k = None self.fisheye_d = None # Used during calibration. self.objpoints = [] # 3d point in real world space self.imgpoints = [] # 2d points in image plane. # Perspective Points self.perspective = None self.previous_window_position = None self.previous_scene_position = None self.corner_drag = None self.matrix = Matrix() self.Bind(wx.EVT_BUTTON, self.on_button_update, self.button_update) self.Bind(wx.EVT_BUTTON, self.on_button_export, self.button_export) self.Bind(wx.EVT_CHECKBOX, self.on_check_fisheye, self.check_fisheye) self.Bind(wx.EVT_CHECKBOX, self.on_check_perspective, self.check_perspective) self.Bind(wx.EVT_SLIDER, self.on_slider_fps, self.slider_fps) self.Bind(wx.EVT_BUTTON, self.on_button_detect, self.button_detect) self.SetDoubleBuffered(True) # end wxGlade self.display_camera.Bind(wx.EVT_PAINT, self.on_paint) self.display_camera.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase) self.display_camera.Bind(wx.EVT_MOTION, self.on_mouse_move) self.display_camera.Bind(wx.EVT_MOUSEWHEEL, self.on_mousewheel) self.display_camera.Bind(wx.EVT_MIDDLE_UP, self.on_mouse_middle_up) self.display_camera.Bind(wx.EVT_MIDDLE_DOWN, self.on_mouse_middle_down) self.display_camera.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_left_down) self.display_camera.Bind(wx.EVT_LEFT_UP, self.on_mouse_left_up) self.display_camera.Bind(wx.EVT_ENTER_WINDOW, lambda event: self.display_camera.SetFocus( )) # Focus follows mouse. self.Bind(wx.EVT_CLOSE, self.on_close, self) self.on_size(None) self.Bind(wx.EVT_SIZE, self.on_size, self) self.camera_lock = threading.Lock() self.process = self.fetch_image self.camera_job = None self.fetch_job = None
def drawSVG(self, svg_attributes, attributes, paths): global SCALE global SUBSAMPLING global SIMPLIFY global SIMPLIFYHQ global TRACEWIDTH out = '' svgWidth = 0 svgHeight = 0 if 'viewBox' in svg_attributes.keys(): if svg_attributes['viewBox'].split()[2] != '0': svgWidth = str( round(float(svg_attributes['viewBox'].split()[2]), 2)) svgHeight = str( round(float(svg_attributes['viewBox'].split()[3]), 2)) else: svgWidth = svg_attributes['width'] svgHeight = svg_attributes['height'] else: svgWidth = svg_attributes['width'] svgHeight = svg_attributes['height'] specifiedWidth = svg_attributes['width'] if 'mm' in specifiedWidth: specifiedWidth = float(specifiedWidth.replace('mm', '')) SCALE = specifiedWidth / float(svgWidth) if self.verbose: print("SVG width detected in mm \\o/") elif 'in' in specifiedWidth: specifiedWidth = float(specifiedWidth.replace('in', '')) * 25.4 SCALE = specifiedWidth / float(svgWidth) if self.verbose: print("SVG width detected in inches") else: SCALE = (self.scaleFactor * 25.4) / 150 if self.verbose: print("SVG width not found, guessing based on scale factor") self.exportHeight = float(svgHeight) * SCALE if len(paths) == 0: print("No paths found. Did you use 'Object to path' in Inkscape?") i = 0 out = [] while i < len(paths): if self.verbose: print('Translating Path ' + str(i + 1) + ' of ' + str(len(paths))) # Apply the tranform from this svg object to actually transform the points # We need the Matrix object from svgelements but we can only matrix multiply with # svgelements' version of the Path object so we're gonna do some dumb stuff # to launder the Path object from svgpathtools through a d-string into # svgelements' version of Path. Luckily, the Path object from svgelements has # backwards compatible .point methods pathTransform = Matrix('') if 'transform' in attributes[i].keys(): pathTransform = Matrix(attributes[i]['transform']) if self.verbose: print('...Applying Transforms') path = elPath(paths[i].d()) * pathTransform path = elPath(path.d()) # Another stage of transforms that gets applied to all paths # in order to shift the label around the origin tx = { 'l': 0, 'c': 0 - (float(svgWidth) / 2), 'r': 0 - float(svgWidth) } ty = {'t': 250, 'c': 150, 'b': 50} path = elPath(paths[i].d()) * Matrix.translate( tx[self.originPos[1]], ty[self.originPos[0]]) path = elPath(path.d()) style = 0 if 'style' in attributes[i].keys(): style = styleParse(attributes[i]['style']) if 'fill' in attributes[i].keys(): filled = attributes[i]['fill'] != 'none' and attributes[i][ 'fill'] != '' elif 'style' in attributes[i].keys(): filled = style['fill'] != 'none' and style['fill'] != '' else: filled = False if 'stroke' in attributes[i].keys(): stroked = attributes[i]['stroke'] != 'none' and attributes[i][ 'stroke'] != '' elif 'style' in attributes[i].keys(): stroked = style['stroke'] != 'none' and style['stroke'] != '' else: stroked = False if not filled and not stroked: i += 1 continue # not drawable (clip path?) SUBSAMPLING = self.subSampling TRACEWIDTH = str(self.traceWidth) l = path.length() divs = round(l * SUBSAMPLING) if divs < 3: divs = 3 maxLen = l * 2 * SCALE / divs p = path.point(0) p = complex(p.real * SCALE, p.imag * SCALE) last = p polys = [] points = [] s = 0 while s <= divs: p = path.point(s * 1 / divs) p = complex(p.real * SCALE, p.imag * SCALE) if dist(p, last) > maxLen: if len(points) > 1: points = simplify(points, SIMPLIFY, SIMPLIFYHQ) polys.append(points) points = [p] else: points.append(p) last = p s += 1 if len(points) > 1: points = simplify(points, SIMPLIFY, SIMPLIFYHQ) polys.append(points) if filled: polys = unpackPoly(polys) for points in polys: if len(points) < 2: return _points = [] if filled: points.append( points[0]) # re-add final point so we loop around for p in points: precisionX = round(p.real, 8) precisionY = round(p.imag - self.exportHeight, 8) _points += [(precisionX, precisionY)] out += [_points] i += 1 self.polys = out return out
def drawSVG(svg_attributes, attributes, paths): global SCALE global SUBSAMPLING global SIMPLIFY global SIMPLIFYHQ global TRACEWIDTH out = '' svgWidth = 0 svgHeight = 0 if 'viewBox' in svg_attributes.keys(): if svg_attributes['viewBox'].split()[2] != '0': svgWidth = str( round(float(svg_attributes['viewBox'].split()[2]), 2)) svgHeight = str( round(float(svg_attributes['viewBox'].split()[3]), 2)) else: svgWidth = svg_attributes['width'] svgHeight = svg_attributes['height'] else: svgWidth = svg_attributes['width'] svgHeight = svg_attributes['height'] specifiedWidth = svg_attributes.get('width') if specifiedWidth == None: specifiedWidth = "None" if 'mm' in specifiedWidth: specifiedWidth = float(specifiedWidth.replace('mm', '')) SCALE = specifiedWidth / float(svgWidth) if args.verbose: print("SVG width detected in mm \\o/") elif 'in' in specifiedWidth: specifiedWidth = float(specifiedWidth.replace('in', '')) * 25.4 SCALE = specifiedWidth / float(svgWidth) if args.verbose: print("SVG width detected in inches") else: SCALE = (args.scaleFactor * 25.4) / 150 if args.verbose: print("SVG width not found, guessing based on scale factor") exportHeight = float(svgHeight) * SCALE if args.outMode == "b": out += "CHANGE layer " + str(args.eagleLayerNumber) + \ "; CHANGE rank 3; CHANGE pour solid; SET WIRE_BEND 2;\n" if args.outMode == "ls": out += "CHANGE layer " + str(args.eagleLayerNumber) + \ "; CHANGE pour solid; Grid mm; SET WIRE_BEND 2;\n" if len(paths) == 0: print("No paths found. Did you use 'Object to path' in Inkscape?") anyVisiblePaths = False i = 0 while i < len(paths): if args.verbose: print('Translating Path ' + str(i + 1) + ' of ' + str(len(paths))) # Apply the tranform from this svg object to actually transform the points # We need the Matrix object from svgelements but we can only matrix multiply with # svgelements' version of the Path object so we're gonna do some dumb stuff # to launder the Path object from svgpathtools through a d-string into # svgelements' version of Path. Luckily, the Path object from svgelements has # backwards compatible .point methods pathTransform = Matrix('') if 'transform' in attributes[i].keys(): pathTransform = Matrix(attributes[i]['transform']) if args.verbose: print('...Applying Transforms') path = elPath(paths[i].d()) * pathTransform path = elPath(path.d()) # Another stage of transforms that gets applied to all paths # in order to shift the label around the origin tx = {'l': 0, 'c': 0 - (float(svgWidth) / 2), 'r': 0 - float(svgWidth)} ty = {'t': 250, 'c': 150, 'b': 50} path = elPath(paths[i].d()) * Matrix.translate(tx[args.originPos[1]], ty[args.originPos[0]]) path = elPath(path.d()) style = 0 if 'style' in attributes[i].keys(): style = styleParse(attributes[i].get('style')) if 'fill' in attributes[i].keys(): filled = attributes[i].get('fill') != 'none' and attributes[i].get( 'fill') != '' elif 'style' in attributes[i].keys(): filled = style.get('fill') != 'none' and style.get('fill') != '' else: filled = False if 'stroke' in attributes[i].keys(): stroked = attributes[i].get( 'stroke') != 'none' and attributes[i].get('stroke') != '' elif 'style' in attributes[i].keys(): stroked = style.get('stroke') != 'none' and style.get( 'stroke') != '' else: stroked = False if not filled and not stroked: i += 1 continue # not drawable (clip path?) SUBSAMPLING = args.subSampling TRACEWIDTH = str(args.traceWidth) anyVisiblePaths = True l = path.length() divs = round(l * SUBSAMPLING) if divs < 3: divs = 3 maxLen = l * 2 * SCALE / divs p = path.point(0) p = complex(p.real * SCALE, p.imag * SCALE) last = p polys = [] points = [] s = 0 while s <= divs: p = path.point(s * 1 / divs) p = complex(p.real * SCALE, p.imag * SCALE) if dist(p, last) > maxLen: if len(points) > 1: points = simplify(points, SIMPLIFY, SIMPLIFYHQ) polys.append(points) points = [p] else: points.append(p) last = p s += 1 if len(points) > 1: points = simplify(points, SIMPLIFY, SIMPLIFYHQ) polys.append(points) if filled: polys = unpackPoly(polys) for points in polys: if len(points) < 2: return scriptLine = '' if filled: points.append( points[0]) # re-add final point so we loop around if args.outMode != "lib": if args.outMode == "b": scriptLine += "polygon " + args.signalName + " " + TRACEWIDTH + "mm " if args.outMode == "ls": scriptLine += "polygon " + TRACEWIDTH + "mm " for p in points: precisionX = '{0:.2f}'.format(round(p.real, 6)) precisionY = '{0:.2f}'.format( round(exportHeight - p.imag, 6)) scriptLine += '(' + precisionX + 'mm ' + precisionY + 'mm) ' scriptLine += ';' else: scriptLine += "<polygon width=\"" + TRACEWIDTH + "\" layer=\"" + str( args.eagleLayerNumber) + "\">\n" for p in points: precisionX = '{0:.2f}'.format(round(p.real, 6)) precisionY = '{0:.2f}'.format( round(exportHeight - p.imag, 6)) scriptLine += "<vertex x=\"" + precisionX + "\" y=\"" + precisionY + "\"/>\n" scriptLine += "</polygon>" out += scriptLine + '\n' i += 1 if not anyVisiblePaths: print("No paths with fills or strokes found.") return out