我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用wx.Image()。
def UpdateImage2D(self): object = self.object imagedata = numpy.array(object, dtype=numpy.double) imagedata[imagedata < 1e-6] = 1.0 imagedata = numpy.log(imagedata) imagedata = imagedata - imagedata.min() if imagedata.max() > 0: imagedata = (255.0/imagedata.max())*imagedata else: imagedata = 255.0*imagedata imagedatalow = numpy.uint8(imagedata) self.impil = Image.fromarray(imagedatalow, 'L').resize((self.sx,self.sy)) self.imwx = wx.EmptyImage( self.impil.size[0], self.impil.size[1] ) self.imwx.SetData( self.impil.convert( 'RGB' ).tobytes() ) bitmap = wx.BitmapFromImage(self.imwx) self.bmp = bitmap self.image.SetBitmap(bitmap) self.Refresh() self.Layout()
def graph_caps(self, cap_files, graphdir): OS = "linux" if len(cap_files) > 1: print("make caps graph") if OS == "linux": print("Yay linux") os.system("../visualisation/caps_graph.py caps="+capsdir+" out="+graphdir) elif OS == 'win': print("oh, windows, i prefer linux but no worries...") os.system("python ../visualisation/caps_graph.py caps="+capsdir+" out="+graphdir) else: print("skipping graphing caps - disabled or no caps to make graphs with") if os.path.exists(graphdir+'caps_filesize_graph.png'): cap_size_graph_path = wx.Image(graphdir+'caps_filesize_graph.png', wx.BITMAP_TYPE_ANY) return cap_size_graph_path else: print("NOT ENOUGH CAPS GRAPH SO USING BLANK THUMB") blankimg = wx.EmptyImage(width=100, height=100, clear=True) return blankimg
def __init__( self, parent ): win_height = parent.GetSize()[1] win_width = parent.GetSize()[0] w_space_left = win_width - 285 wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = (285, 0), size = wx.Size(w_space_left , 800), style = wx.TAB_TRAVERSAL ) ## Draw UI elements png = wx.Image('./config_info.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() wx.StaticBitmap(self, -1, png, (0, 0), (png.GetWidth(), png.GetHeight())) #SDcard details config_info_pnl.boxname_text = wx.TextCtrl(self, pos=(25, 150), size=(265,65)) config_info_pnl.location_text = wx.StaticText(self, label='locations', pos=(520, 120), size=(200,30)) config_info_pnl.config_text = wx.StaticText(self, label='config', pos=(520, 185), size=(200,30)) config_info_pnl.lamp_text = wx.StaticText(self, label='lamp', pos=(10, 330), size=(200,30)) config_info_pnl.dht_text = wx.StaticText(self, label='dht', pos=(10, 415), size=(200,30)) config_info_pnl.gpio_table = self.GPIO_list(self, 1) config_info_pnl.gpio_table.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onDoubleClick_GPIO)
def OnRadioSelect(self, event): rselect = self.rb.GetStringSelection() if rselect == 'None': self.vbox2.ShowItems(False) self.dataview.Hide() if rselect == 'Array': self.vbox2.ShowItems(False) self.dataview.Show() if rselect == 'Image': self.vbox2.ShowItems(True) if hasattr(self.object, 'shape'): if len(self.object.shape) != 3: self.hbox2.ShowItems(False) self.hbox3.ShowItems(False) else: self.hbox2.ShowItems(False) self.hbox3.ShowItems(False) self.dataview.Hide() self.Layout() item = self.tree.GetSelection() self.SelTreeItem(item)
def view(self, file): ''' Called when loading a new image. Pass arg bytesIO image file ''' img = wx.Image(file, wx.BITMAP_TYPE_ANY) # scale the image, preserving the aspect ratio W = img.GetWidth() H = img.GetHeight() if W > H: NewW = self.PhotoMaxSize NewH = self.PhotoMaxSize * H / W else: NewH = self.PhotoMaxSize NewW = self.PhotoMaxSize * W / H img = img.Scale(NewW, NewH) self.imageCtrl.SetBitmap(wx.BitmapFromImage(img)) self.panel.Refresh()
def loadPIL_LUT(self, dataset): if not have_PIL: raise ImportError("Python Imaging Library is not available. See http://www.pythonware.com/products/pil/ to download and install") if('PixelData' not in dataset): raise TypeError("Cannot show image -- DICOM dataset does not have pixel data") if('WindowWidth' not in dataset) or ('WindowCenter' not in dataset): # can only apply LUT if these values exist bits = dataset.BitsAllocated samples = dataset.SamplesPerPixel if bits == 8 and samples == 1: mode = "L" elif bits == 8 and samples == 3: mode = "RGB" elif bits == 16: # not sure about this -- PIL source says is 'experimental' and no documentation. mode = "I;16" # Also, should bytes swap depending on endian of file and system?? else: raise TypeError("Don't know PIL mode for %d BitsAllocated and %d SamplesPerPixel" % (bits, samples)) size = (dataset.Columns, dataset.Rows) im = PIL.Image.frombuffer(mode, size, dataset.PixelData, "raw", mode, 0, 1) # Recommended to specify all details by http://www.pythonware.com/library/pil/handbook/image.htm else: image = self.get_LUT_value(dataset.pixel_array, dataset.WindowWidth, dataset.WindowCenter) im = PIL.Image.fromarray(image).convert('L') # Convert mode to L since LUT has only 256 values: http://www.pythonware.com/library/pil/handbook/image.htm return im
def __init__(self, parent): """Constructor""" self.notUseDetaul = None wx.Panel.__init__(self, parent=parent, size = (500,800)) B = wx.StaticBox(self, -1) BSizer = wx.StaticBoxSizer(B, wx.VERTICAL) self.imagesDir = os.path.join(".", "images") self.screenShotDir = os.path.join(".", "screenShot") self.defaultScreenShotImage = wx.Image(os.path.join(self.imagesDir, "default.png"), wx.BITMAP_TYPE_PNG).ConvertToBitmap() self.screenShot = wx.StaticBitmap(self,-1, self.defaultScreenShotImage) self.screenShot.Bind(wx.EVT_LEFT_DOWN, self.DrawOrReloadAll) self.statusBar = wx.StaticText(self, -1, "") BSizer.Add(self.statusBar) BSizer.Add(self.screenShot,5,wx.EXPAND, 5) self.SetSizer(BSizer) pub.subscribe(self.updateStatus, "update") pub.subscribe(self.DrawFromSelectedNode, "DrawFromSelectedNode") pub.subscribe(self.DoSwipeOrInput, "DoSwipeOrInput") self.hasDrew = False
def __init__(self, redirect=False, filename=None): wx.App.__init__(self, redirect, filename) BASEURL = "http://127.0.0.1:8000" self.InitUpdates(BASEURL, BASEURL + "/" + 'ChangeLog.txt') self.SetAppDisplayName('Image Viewer') self.CheckForUpdate() self.frame = wx.Frame(None, title='Photo Control') self.panel = wx.Panel(self.frame) self.PhotoMaxSize = 500 self.createWidgets() self.frame.Show()
def onView(self): """ Attempts to load the image and display it """ filepath = self.photoTxt.GetValue() img = wx.Image(filepath, wx.BITMAP_TYPE_ANY) # scale the image, preserving the aspect ratio W = img.GetWidth() H = img.GetHeight() if W > H: NewW = self.PhotoMaxSize NewH = self.PhotoMaxSize * H / W else: NewH = self.PhotoMaxSize NewW = self.PhotoMaxSize * W / H img = img.Scale(NewW,NewH) self.imageCtrl.SetBitmap(wx.Bitmap(img)) self.panel.Refresh() self.mainSizer.Fit(self.frame)
def loadImage(self, image): """ Load the image into the application for display """ image_name = os.path.basename(image) img = wx.Image(image, wx.BITMAP_TYPE_ANY) # scale the image, preserving the aspect ratio W = img.GetWidth() H = img.GetHeight() if W > H: NewW = self.photoMaxSize NewH = self.photoMaxSize * H / W else: NewH = self.photoMaxSize NewW = self.photoMaxSize * W / H img = img.Scale(NewW,NewH) self.imageCtrl.SetBitmap(wx.BitmapFromImage(img)) self.imageLabel.SetLabel(image_name) self.Refresh() Publisher().sendMessage("resize", "")
def draw(self): # Image img = self.bmp.ConvertToImage() img = img.Rescale(320,240) self.image_widget.SetBitmap( img.ConvertToBitmap() ) # Joystick x = np.asarray(self.plotData) self.axes.plot(range(0,self.plotMem), x[:,0], 'r') self.axes.hold(True) self.axes.plot(range(0,self.plotMem), x[:,1], 'b') self.axes.plot(range(0,self.plotMem), x[:,2], 'g') self.axes.plot(range(0,self.plotMem), x[:,3], 'k') self.axes.plot(range(0,self.plotMem), x[:,4], 'y') self.axes.hold(False) self.PlotCanvas.draw()
def onSelect(self,event): if self.image_name: if self.n_points != None and len(self.coords[self.image_name]) != self.n_points: print "ERROR: incorrect number of points." self.image_name = event.GetString() if not self.coords.has_key(self.image_name): self.coords[self.image_name] = [] filename = os.path.join(self.image_dir,self.image_name) self.current_image = wx.Image(filename) self.first_click = True self.DisplayImage()
def BuildTimeline(self,dbfile): for child in self.panel3.GetChildren(): logging.exception(child) child.Destroy() # the last frame is latestfram = self.cur.execute("SELECT * FROM Timeline ORDER BY Image DESC LIMIT 1") #latestfram = self.cur.execute("SELECT * FROM Timeline WHERE ID = (SELECT MAX(ID) FROM TABLE) AND Blackspot = 0"); try: for entry in latestfram: self.framlog = int(entry[1].split('.')[0]) self.framlog += 1 logging.exception(self.framlog) except: logging.exception('Looking for last frame but did not find.') pass # timeline contains tbl_timeline = self.cur.execute("SELECT * FROM Timeline WHERE Blackspot=0") for entry in tbl_timeline: img = self.MakeThumbnail(os.path.join(self.imgdir, entry[1]), self.thumbsize) self.imageCtrl = wx.StaticBitmap(self.panel3, wx.ID_ANY, wx.BitmapFromImage(img),name=entry[1]) self.imageCtrl.SetBitmap(wx.BitmapFromImage(img)) self.imageCtrl.Bind( wx.EVT_LEFT_DOWN, self.OnLeftClick ) self.imageCtrl.Bind( wx.EVT_LEFT_UP, self.OnLeftRelease ) logging.exception(self.imageCtrl.GetId() ) self.hbox2.Add( self.imageCtrl, 0, wx.ALL, 5 ) self.Layout() self.panel3.SetFocus() self.BindKeys(dbfile) self.hbox2.Layout() self.panel3.Refresh() self.panel3.Update() self.Refresh()
def MakeThumbnail(self, filepath, PhotoMaxSize): img = wx.Image(filepath, wx.BITMAP_TYPE_ANY) # scale image, preserve aspect ratio W = img.GetWidth() H = img.GetHeight() if W > H: NewW = PhotoMaxSize NewH = PhotoMaxSize * H / W else: NewH = PhotoMaxSize NewW = PhotoMaxSize * W / H img = img.Scale(NewW,NewH) imgb = wx.BitmapFromImage(img) return img
def OnLeftRelease(self,e): self.player.stop() self.brec.SetBitmapLabel(self.brecxicon) self.bplay.SetBitmapLabel(self.bplayicon) if self.hasSelected: #the frame selected was clicked img = self.MakeThumbnail(os.path.join(self.imgdir, self.selected.GetName() ), self.thumbsize) self.selected.SetBitmap(wx.BitmapFromImage(img) ) self.hasSelected = True self.previous = 0 self.player.play() self.viewport.Refresh() self.brec.SetBitmapLabel(self.brecicon) if not self.hasSelected: # we clicked something new # get new selection self.selected = e.GetEventObject() # highlight new selection img = self.MakeThumbnail(os.path.join(self.imgdir, self.selected.GetName() ), self.thumbsize + 3) imgb = wx.BitmapFromImage(img) dc = wx.MemoryDC(imgb) staricon = wx.Image(os.path.join(os.path.dirname(__file__),'..','..','stopgo','images','select.png') ) star = wx.BitmapFromImage(staricon) dc.DrawBitmap(star,133,0) dc.SelectObject(wx.NullBitmap) del dc control = wx.StaticBitmap(self, -1, imgb) self.selected.SetBitmap(imgb) self.hasSelected = True self.previous = self.selected.GetId() #paint canvas img = self.MakeThumbnail(os.path.join( self.imgdir, self.selected.GetName() ), self.screenHeight*.9) self.GetStatusBar().SetStatusText(self.selected.GetName(), 0) self.PaintCanvas(img) self.viewport.Refresh()
def DBQuit(self,dbfile): self.cur = self.con.cursor() self.cur.execute("SELECT Image FROM Timeline WHERE Blackspot==1") blacklist = self.cur.fetchall() for blackitem in blacklist: os.remove(os.path.join(self.imgdir,blackitem[0]) ) self.cur.execute("DELETE FROM Timeline WHERE Blackspot=1") self.con.commit() #self.con.close() return 42
def load_zad(self, file_path, fit=True): img = wx.Image(file_path, wx.BITMAP_TYPE_ANY) if fit: w, h = img.GetWidth(), img.GetHeight() max_w, max_h = self.images_panel.GetSize() target_ratio = min(max_w / float(w), max_h / float(h)) new_w, new_h = [int(x * target_ratio) for x in (w, h)] img = img.Scale(new_w, new_h, wx.IMAGE_QUALITY_HIGH) self.images_panel.drawable_bitmap = wx.Bitmap(img) self.images_panel.Refresh()
def no_show(self): self.images_panel.drawable_bitmap = \ wx.Bitmap(wx.Image(*self.images_panel.drawable_bitmap.GetSize())) self.images_panel.Refresh()
def __init__(self, parent, title): style = wx.DEFAULT_FRAME_STYLE & ~( wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX|wx.CLOSE_BOX) wx.Frame.__init__(self, parent, title=title, style=style, size=(400,60)) self.textbox = wx.TextCtrl(self) img = wx.Image("matags.png", wx.BITMAP_TYPE_ANY) bmp = wx.Bitmap(img) self.icon = wx.Icon() self.icon.CopyFromBitmap(bmp) self.SetIcon(self.icon) self.tbIcon = wx.adv.TaskBarIcon() self.tbIcon.SetIcon(self.icon) self.Show(True) self.Centre() self.reg_hot_keys() self.Bind(wx.EVT_HOTKEY, self.on_extract_tag, id=self.hotkeys['extract_tag'][0]) self.Bind(wx.EVT_HOTKEY, self.on_close, id=self.hotkeys['quit'][0]) self.Bind(wx.EVT_HOTKEY, self.on_activate, id=self.hotkeys['activate'][0]) self.Bind(wx.EVT_HOTKEY, self.on_refresh, id=self.hotkeys['refresh'][0]) self.textbox.Bind(wx.EVT_CHAR, self.check_key) # do not use EVT_KEY_DOWN, # it becomes difficult to get lower case # self.textbox.Bind(wx.EVT_KEY_DOWN, self.check_key) # self.Bind(wx.EVT_CLOSE, self.on_close) self.Bind(wx.EVT_ICONIZE, self.on_iconify) self.matags = MaTags() # try: # except Exception as e: # self.textbox.ChangeValue(e.args[0].decode('utf8', 'ignore')) # self.textbox.Disable()
def __init__(self, parent): logo = wx.Image(os.path.dirname(__file__) + '/images/CEBL3_splash.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap() #wx.adv.SplashScreen.__init__(self, # wxpython3 wx.SplashScreen.__init__(self, parent=parent, milliseconds=2000, bitmap=logo, #splashStyle=wx.adv.SPLASH_CENTER_ON_SCREEN | wx.adv.SPLASH_TIMEOUT) # wxpython3 splashStyle=wx.SPLASH_CENTER_ON_SCREEN | wx.SPLASH_TIMEOUT)
def updatelastpic(self, lframe): capsdir = self.capsfolder_box.GetValue() last_pic = str(capsdir + cap_files[lframe]) if os.path.exists(last_pic): last_pic = wx.Image(last_pic, wx.BITMAP_TYPE_ANY) last_pic = self.scale_pic(last_pic, 500) self.last_pic.SetBitmap(wx.BitmapFromImage(last_pic)) lpicdate = self.date_from_fn(cap_files[lframe]) self.lpic_text.SetLabel('Frame ' + str(lframe) + ' - ' + str(lpicdate)) else: self.last_pic.SetBitmap(wx.EmptyBitmap(10,10)) self.fpic_text.SetLabel('end')
def updatefirstpic(self, fframe): capsdir = self.capsfolder_box.GetValue() first_pic = str(capsdir + cap_files[fframe]) if os.path.exists(first_pic): first_pic = wx.Image(first_pic, wx.BITMAP_TYPE_ANY) first_pic = self.scale_pic(first_pic, 500) fpicdate = self.date_from_fn(cap_files[fframe]) self.fpic_text.SetLabel('Frame ' + str(fframe) + ' - ' + str(fpicdate)) self.first_pic.SetBitmap(wx.BitmapFromImage(first_pic)) else: self.first_pic.SetBitmap(wx.EmptyBitmap(10,10)) self.fpic_text.SetLabel('start')
def __init__( self, parent ): win_height = parent.GetSize()[1] win_width = parent.GetSize()[0] w_space_left = win_width - 285 wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = (285, 0), size = wx.Size(w_space_left , 800), style = wx.TAB_TRAVERSAL ) ## Draw UI elements png = wx.Image('./sysconf.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() wx.StaticBitmap(self, -1, png, (0, 0), (png.GetWidth(), png.GetHeight())) #SDcard details system_info_pnl.sys_hdd_total = wx.StaticText(self, label='total;', pos=(250, 180), size=(200,30)) system_info_pnl.sys_hdd_remain = wx.StaticText(self, label='free;', pos=(250, 250), size=(200,30)) system_info_pnl.sys_hdd_used = wx.StaticText(self, label='Used;', pos=(250, 215), size=(200,30)) system_info_pnl.sys_pigrow_folder = wx.StaticText(self, label='Pigrow folder;', pos=(250, 285), size=(200,30)) #Software details system_info_pnl.sys_os_name = wx.StaticText(self, label='os installed;', pos=(250, 365), size=(200,30)) #system_info_pnl.sys_pigrow_version = wx.StaticText(self, label='pigrow version;', pos=(250, 405), size=(200,30)) system_info_pnl.sys_pigrow_update = wx.StaticText(self, label='Pigrow update status', pos=(250, 450), size=(200,30)) #wifi deatils system_info_pnl.sys_network_name = wx.StaticText(self, label='network name', pos=(250, 535), size=(200,30)) system_info_pnl.wifi_list = wx.StaticText(self, label='wifi list', pos=(140, 620), size=(200,30)) #camera details system_info_pnl.sys_camera_info = wx.StaticText(self, label='camera info', pos=(585, 170), size=(200,30)) #power level warning details system_info_pnl.sys_power_status = wx.StaticText(self, label='power status', pos=(625, 390), size=(200,30)) # Raspberry Pi revision system_info_pnl.sys_pi_revision = wx.StaticText(self, label='raspberry pi version', pos=(625, 450), size=(200,30)) # Pi datetime vs local pc datetime system_info_pnl.sys_pi_date = wx.StaticText(self, label='datetime on pi', pos=(625, 495), size=(500,30)) system_info_pnl.sys_pc_date = wx.StaticText(self, label='datetime on local pc', pos=(625, 525), size=(200,30)) #system_info_pnl.sys_time_diff = wx.StaticText(self, label='difference', pos=(700, 555), size=(200,30)) # # # ### pigrow Config pannel # #
def __init__( self, parent ): win_height = parent.GetSize()[1] win_width = parent.GetSize()[0] w_space_left = win_width - 285 wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = (285, 0), size = wx.Size(w_space_left , 800), style = wx.TAB_TRAVERSAL ) #set blank variables localfiles_info_pnl.local_path = "" ## Draw UI elements png = wx.Image('./localfiles.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() wx.StaticBitmap(self, -1, png, (0, 0), (png.GetWidth(), png.GetHeight())) # placing the information boxes localfiles_info_pnl.local_path_txt = wx.StaticText(self, label='local path', pos=(220, 80), size=(200,30)) #local photo storage info localfiles_info_pnl.caps_folder = 'caps' localfiles_info_pnl.folder_text = wx.StaticText(self, label=' ' + localfiles_info_pnl.caps_folder, pos=(720, 130), size=(200,30)) localfiles_info_pnl.photo_text = wx.StaticText(self, label='photo text', pos=(575, 166), size=(170,30)) localfiles_info_pnl.first_photo_title = wx.StaticText(self, label='first image', pos=(575, 290), size=(170,30)) localfiles_info_pnl.last_photo_title = wx.StaticText(self, label='last image', pos=(575, 540), size=(170,30)) #file list boxes localfiles_info_pnl.config_files = self.config_file_list(self, 1, pos=(5, 160), size=(550, 200)) localfiles_info_pnl.config_files.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onDoubleClick_config) localfiles_info_pnl.logs_files = self.logs_file_list(self, 1, pos=(5, 390), size=(550, 200)) localfiles_info_pnl.logs_files.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onDoubleClick_logs) #localfiles_info_pnl.config_files = self.config_file_list(self, 1, pos=(5, 160), size=(550, 200)) # localfiles_info_pnl.config_files.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onDoubleClick_config) #cron info text localfiles_info_pnl.cron_info = wx.StaticText(self, label='cron info', pos=(290, 635), size=(200,30))
def draw_photo_folder_images(self, first_pic, last_pic): # load and display first image first = wx.Image(first_pic, wx.BITMAP_TYPE_ANY) first = first.Scale(225, 225, wx.IMAGE_QUALITY_HIGH) first = first.ConvertToBitmap() localfiles_info_pnl.photo_folder_first_pic = wx.StaticBitmap(self, -1, first, (620, 310), (first.GetWidth(), first.GetHeight())) # load and display last image last = wx.Image(last_pic, wx.BITMAP_TYPE_ANY) last = last.Scale(225, 225, wx.IMAGE_QUALITY_HIGH) last = last.ConvertToBitmap() localfiles_info_pnl.photo_folder_last_pic = wx.StaticBitmap(self, -1, last, (620, 565), (last.GetWidth(), last.GetHeight()))
def __init__( self, parent ): wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = (285, 0), size = wx.Size( 910,800 ), style = wx.TAB_TRAVERSAL ) self.SetBackgroundColour((150,210,170)) #TESTING ONLY REMOVE WHEN SIZING IS DONE AND ALL THAT BUSINESS png = wx.Image('./splash.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap() wx.StaticBitmap(self, -1, png, (0, 0), (png.GetWidth(), png.GetHeight()))
def UpdateImage(self, axis, position): object = self.object idx = position - 1 if axis == 1: imagedata = object[idx,:,:] elif axis == 2: imagedata = object[:,idx,:] else: imagedata = object[:,:,idx] imagedata[imagedata < 1e-6] = 1.0 imagedata = numpy.log(imagedata) imagedata = imagedata - imagedata.min() if imagedata.max() > 0: imagedata = (255.0/imagedata.max())*imagedata else: imagedata = 255.0*imagedata imagedatalow = numpy.uint8(imagedata) self.impil = Image.fromarray(imagedatalow, 'L').resize((self.sx,self.sy)) if IsNotWX4(): self.imwx = wx.EmptyImage( self.impil.size[0], self.impil.size[1] ) else: self.imwx = wx.Image( self.impil.size[0], self.impil.size[1] ) self.imwx.SetData( self.impil.convert( 'RGB' ).tobytes() ) if IsNotWX4(): bitmap = wx.BitmapFromImage(self.imwx) else: bitmap = wx.Bitmap(self.imwx) if IsNotWX4(): self.bmp = wx.BitmapFromImage(self.imwx) else: self.bmp = wx.Bitmap(self.imwx) self.image.SetBitmap(bitmap) self.Refresh() self.Layout()
def UpdateImage(self, axis, position): object = self.object idx = position - 1 if axis == 1: imagedata = numpy.array(object[idx,:,:]) elif axis == 2: imagedata = numpy.array(object[:,idx,:]) else: imagedata = numpy.array(object[:,:,idx]) imagedata[imagedata < 1e-6] = 1.0 imagedata = numpy.log(imagedata) imagedata = imagedata - imagedata.min() if imagedata.max() > 0: imagedata = (255.0/imagedata.max())*imagedata else: imagedata = 255.0*imagedata imagedatalow = numpy.uint8(imagedata) self.impil = Image.fromarray(imagedatalow, 'L').resize((self.sx,self.sy)) if IsNotWX4(): self.imwx = wx.EmptyImage( self.impil.size[0], self.impil.size[1] ) else: self.imwx = wx.Image( self.impil.size[0], self.impil.size[1] ) self.imwx.SetData( self.impil.convert( 'RGB' ).tobytes() ) if IsNotWX4(): bitmap = wx.BitmapFromImage(self.imwx) else: bitmap = wx.Bitmap(self.imwx) self.bmp = bitmap self.image.SetBitmap(bitmap) self.Refresh() self.Layout()
def __init__(self, parent): self.panel = wx.ScrolledWindow.__init__(self, parent) self.SetScrollRate(5, 5) self.panelphase = self.GetParent().panelphase self.panelvisual = self.GetParent().panelvisual self.cmvbox = wx.BoxSizer(wx.VERTICAL) self.cmhbox = [] self.imglist = [] self.sellist = [] self.rb = [] self.chkb = [] array = self.panelphase.cms[0][1] dc = wx.ScreenDC() dc.SetFont(self.panelvisual.font) w,h = dc.GetTextExtent("TestString") height = h if IsNotWX4(): image = wx.EmptyImage(array.shape[0],height) else: image = wx.Image(array.shape[0],height) newarray = numpy.zeros((height, array.shape[0], 3), dtype=numpy.uint8) for i in range(self.panelphase.cms.shape[0]): self.cmhbox.append( wx.BoxSizer(wx.HORIZONTAL) ) name = self.panelphase.cms[i][0] array = self.panelphase.cms[i][1] for j in range(height): newarray[j,:,:] = numpy.uint8(255.0*array) image.SetData( newarray.tostring()) bmp = image.ConvertToBitmap() self.imglist.append(wx.StaticBitmap(self, -1, bmp)) self.rb.append( wx.RadioButton(self, -1, label=name, size=(160, height) ) ) self.cmhbox[-1].Add(self.rb[-1], 0) self.cmhbox[-1].Add((5, -1)) self.cmhbox[-1].Add(self.imglist[-1], 1, wx.EXPAND) self.chkb.append( wx.CheckBox(self, -1, 'Reverse', size=(160, height)) ) self.cmhbox[-1].Add(self.chkb[-1], 0, wx.EXPAND) self.cmvbox.Add(self.cmhbox[-1], 1, wx.EXPAND) self.SetSizer(self.cmvbox) self.Fit() self.Layout() self.Show()
def OnSize(self, event): # The Buffer init is done here, to make sure the buffer is always # the same size as the Window Size = self.canvas.GetClientSize() if Size.width <= 0 or Size.height <= 0: return Size.width = max(1, Size.width) Size.height = max(1, Size.height) # Make new offscreen bitmap: this bitmap will always have the # current drawing in it, so it can be used to save the image to # a file, or whatever. #self._Buffer = wx.Bitmap(Size.width, Size.height) if IsNotWX4(): self._img = wx.EmptyImage(Size.width,Size.height) self._Buffer = wx.BitmapFromImage(self._img) else: self._img = wx.Image(Size.width,Size.height) self._Buffer = wx.Bitmap(self._img) self._Buffer.SetHeight(Size.height) self._Buffer.SetWidth(Size.width) self._setSize() self.last_PointLabel = None # reset pointLabel if self.last_draw is None: self.Clear() else: graphics, xSpec, ySpec = self.last_draw self._Draw(graphics, xSpec, ySpec)
def display_matches(self): self.mainSizer = wx.BoxSizer(wx.VERTICAL) self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.images = [] self.labels = [] m = self.session.matches() for i in range(len(m)): match = m[i] # Thumb fd = urlopen(match.user.thumbnails[0]) file = io.BytesIO(fd.read()) img = wx.Image(file, wx.BITMAP_TYPE_ANY) self.images.append(wx.StaticBitmap(self.panel, wx.ID_ANY, wx.Bitmap(img))) self.images[i].Bind(wx.EVT_BUTTON, self.onClick) # Label for name self.labels.append(wx.StaticText(self.panel, label=match.user.name)) # Add to sizer self.mainSizer.Add(self.labels[i], 0, wx.ALL, 5) self.mainSizer.Add(self.images[i], 0, wx.ALL, 5) self.mainSizer.Add(self.sizer, 0, wx.ALL, 5) self.panel.SetSizer(self.mainSizer) self.panel.Layout() self.panel.Refresh()
def ConvertWXToPIL(self, bmp): """ Convert wx.Image Into PIL Image. """ width = bmp.GetWidth() height = bmp.GetHeight() im = wx.EmptyImage(width, height) im.fromarray("RGBA", (width, height), bmp.GetData()) return im # ------------------------------------------------------------ # ImFrame.ConvertPILToWX() # Expropriated from Andrea Gavana's # ShapedButton.py in the wxPython dist # ------------------------------------------------------------
def ConvertPILToWX(self, pil, alpha=True): """ Convert PIL Image Into wx.Image. """ if alpha: image = wx.EmptyImage(*pil.size) image.SetData(pil.convert("RGB").tostring()) image.SetAlphaData(pil.convert("RGBA").tostring()[3::4]) else: image = wx.EmptyImage(pil.size[0], pil.size[1]) new_image = pil.convert('RGB') data = new_image.tostring() image.SetData(data) return image
def OnInit(self): """Create the Image Application.""" ImFrame(None, 'wxImage Example') return True # --------------------------------------------------------------------- # If this file is running as main or a standalone test, begin execution here. # ---------------------------------------------------------------------
def updateAfterRotate(self,evt): screenShotPath = os.path.join(os.getcwd(), "screenShot", "screenshot.png") img = Image.open(screenShotPath) out = img.rotate(90,expand=1) out.save(screenShotPath) wx.CallAfter(pub.sendMessage, "update", msg=screenShotPath)
def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,id,title,size=(475,600)) self.parent = parent self.initialize() # Exit exit_button = wx.Button(self, label="Exit", pos=(240+75,550)) exit_button.Bind(wx.EVT_BUTTON, self.onClose) # robot = "/home/pi/Desktop/GoBox/Troubleshooting_GUI/dex.png" # png = wx.Image(robot, wx.BITMAP_TYPE_ANY).ConvertToBitmap() # wx.StaticBitmap(self, -1, png, (0, 0), (png.GetWidth()-320, png.GetHeight()-20)) # self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) # Sets background picture #----------------------------------------------------------------------
def get(self, iconname): try: image = 'img\\' + self.img_dict[iconname] except KeyError: print 'Image: "{}" not found!'.format(iconname) image = 'img\\' + self.img_dict['toilet'] wximage = wx.Image(self.path + image, wx.BITMAP_TYPE_PNG).ConvertToBitmap() return wximage
def ShowSplashScreen(self): from wx.lib.agw.advancedsplash import AdvancedSplash bmp = wx.Image(self.splashPath).ConvertToBitmap() self.splash = AdvancedSplash(None, bitmap=bmp) # process all events # even the events generated by splash themself during showing if wx.Platform == '__WXMSW__': self.splash.Show() self.splash.ProcessEvent(wx.PaintEvent()) else: for i in range(0, 30): wx.Yield() time.sleep(0.01)
def validate_photo(self,path): import wx img = wx.Image(path, wx.BITMAP_TYPE_ANY) # scale the image, preserving the aspect ratio W=img.GetWidth() H=img.GetHeight() if W>120 or H>120 or W<100 or H<100: return False," Image Height and Width must be between 100-120 pixels" return [True]
def __init__(self, parent, id): # create the panel wx.Panel.__init__(self, parent, id) try: # pick an image file you have in the working # folder you can load .jpg .png .bmp or # .gif files image_file = 'big_cat.jpg' bmp1 = wx.Image( image_file, wx.BITMAP_TYPE_ANY).ConvertToBitmap() # image's upper left corner anchors at panel # coordinates (0, 0) self.bitmap1 = wx.StaticBitmap( self, -1, bmp1, (0, 0)) # show some image details str1 = "%s %dx%d" % (image_file, bmp1.GetWidth(), bmp1.GetHeight()) parent.SetTitle(str1) except IOError: print("Image file %s not found" % imageFile) raise SystemExit # button goes on the image --> self.bitmap1 is the # parent self.button1 = wx.Button( self.bitmap1, label='Button1', pos=(8, 8))
def createWidgets(self): instructions = 'Browse for an image' img = wx.Image(240,240) self.imageCtrl = wx.StaticBitmap(self.panel, wx.ID_ANY, wx.Bitmap(img)) instructLbl = wx.StaticText(self.panel, label=instructions) self.photoTxt = wx.TextCtrl(self.panel, size=(200,-1)) browseBtn = wx.Button(self.panel, label='Browse') browseBtn.Bind(wx.EVT_BUTTON, self.onBrowse) self.mainSizer = wx.BoxSizer(wx.VERTICAL) self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.mainSizer.Add(wx.StaticLine(self.panel, wx.ID_ANY), 0, wx.ALL|wx.EXPAND, 5) self.mainSizer.Add(instructLbl, 0, wx.ALL, 5) self.mainSizer.Add(self.imageCtrl, 0, wx.ALL, 5) self.sizer.Add(self.photoTxt, 0, wx.ALL, 5) self.sizer.Add(browseBtn, 0, wx.ALL, 5) self.mainSizer.Add(self.sizer, 0, wx.ALL, 5) self.panel.SetSizer(self.mainSizer) self.mainSizer.Fit(self.frame) self.panel.Layout()
def initToolbar(self): """ Initialize the toolbar """ self.toolbar = self.CreateToolBar() self.toolbar.SetToolBitmapSize((16,16)) open_ico = wx.ArtProvider.GetBitmap( wx.ART_FILE_OPEN, wx.ART_TOOLBAR, (16,16)) openTool = self.toolbar.AddSimpleTool(wx.ID_ANY, open_ico, "Open", "Open an Image Directory") self.Bind(wx.EVT_MENU, self.onOpenDirectory, openTool) self.toolbar.Realize()
def __init__(self): """Constructor""" BASEURL = "http://127.0.0.1:8000" self.InitUpdates(BASEURL, BASEURL + 'ChangeLog.txt') self.CheckForUpdate() frame = ViewerFrame() self.SetTopWindow(frame) self.SetAppDisplayName('Image Viewer') return True
def load(cls, gfx_type, path): if path in cls._gfx_cache[gfx_type]["loaded"]: return cls._gfx_cache[gfx_type]["loaded"][path] gfx = wx.Bitmap(path) if gfx_type == "bitmap" else wx.Image(path) cls._gfx_cache[gfx_type]["loaded"][path] = gfx return gfx
def create_main_panel(self): # Panels self.img_panel = wx.Panel(self) self.joy_panel = wx.Panel(self) self.record_panel = wx.Panel(self) # Images img = wx.Image(320,240) self.image_widget = wx.StaticBitmap(self.img_panel, wx.ID_ANY, wx.Bitmap(img)) # Joystick self.init_plot() self.PlotCanvas = FigCanvas(self.joy_panel, wx.ID_ANY, self.fig) # Recording self.txt_outputDir = wx.TextCtrl(self.record_panel, wx.ID_ANY, pos=(5,0), size=(320,30)) uid = datetime.now().strftime('%Y-%m-%d_%H:%M:%S') self.txt_outputDir.ChangeValue("samples/" + uid) self.btn_record = wx.Button(self.record_panel, wx.ID_ANY, label="Record", pos=(335,0), size=(100,30)) self.Bind(wx.EVT_BUTTON, self.on_btn_record, self.btn_record) self.Bind(wx.EVT_UPDATE_UI, self.on_update_btn_record, self.btn_record) # sizers sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.img_panel, 0, wx.ALL, 5) sizer.Add(self.joy_panel, 0, wx.ALL, 5) mainSizer_v = wx.BoxSizer(wx.VERTICAL) mainSizer_v.Add(sizer, 0 , wx.ALL, 5) mainSizer_v.Add(self.record_panel, 0 , wx.ALL, 5) # finalize layout self.SetAutoLayout(True) self.SetSizer(mainSizer_v) self.Layout()
def NewFile(self,e): wcd='All files(*)|*' dest = 'stopgo_project_' destid = int(time.time()) try: dirname = self.clargs['project'] except OSError: dirname = os.path.expanduser('~') except: dirname = os.path.join(os.path.expanduser('~'),self.myprefs['dir']) sd = wx.FileDialog(self, message='Save file as...', defaultDir=dirname, defaultFile='stopgo_project_' + str(destid), wildcard=wcd, style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) if sd.ShowModal() == wx.ID_OK: projnam = sd.GetFilename() projpath= os.path.join(sd.GetPath(),projnam) # make the directory # the OS does this for us but just in case.. #if not os.path.exists( os.path.dirname(projpath) ): #os.makedirs( os.path.dirname(projpath)) # make image dir os.makedirs( os.path.join(os.path.dirname(projpath),'images')) dbfile = projpath self.imgdir = os.path.join(os.path.dirname(projpath), 'images') logging.exception(dbfile) logging.exception(projpath) logging.exception(self.imgdir) self.con = sq.connect(dbfile, isolation_level=None ) self.cur = self.con.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS Project(Id INTEGER PRIMARY KEY, Path TEXT, Name TEXT, [timestamp] timestamp)") self.cur.execute("CREATE TABLE IF NOT EXISTS Timeline(Id INTEGER PRIMARY KEY, Image TEXT, Blackspot INT)") self.cur.execute("INSERT INTO Project(Path, Name, timestamp) VALUES (?,?,?)", ("images", "StopGo Project", datetime.now() )) #self.con.close() self.BindKeys(dbfile) sb = self.GetStatusBar() stat = os.path.basename(projpath) + ' created' sb.SetStatusText(stat, 0) sb.SetStatusText('', 1) sd.Destroy()