Skip to content

Instantly share code, notes, and snippets.

@nmz787
Last active January 3, 2020 08:28
Show Gist options
  • Save nmz787/e442c07a897d483e2a9a0e1d99dcb709 to your computer and use it in GitHub Desktop.
Save nmz787/e442c07a897d483e2a9a0e1d99dcb709 to your computer and use it in GitHub Desktop.
PBM image viewer for gigapixel files - CTRL O to open a file, press enter in the text boxes to update screen
__license__ = """
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
As a special exception, the copyright holders of this library
hereby recind Section 3 of the GNU Lesser General Public License. This
means that you MAY NOT apply the terms of the ordinary GNU General
Public License instead of this License to any given copy of the
Library. This has been done to prevent users of the Library from being
denied access or the ability to use future improvements.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
import wx
class BufferedCanvas(wx.Panel):
"""
Implements a double-buffered, flicker-free canvas widget.
Standard usage is to subclass this class, and override the
draw method. The draw method is passed a device context, which
should be used to do your drawing.
Also, you should NOT call dc.BeginDrawing() and dc.EndDrawing() --
these methods are automatically called for you, although you still
need to manually clear the device context.
If you want to force a redraw (for whatever reason), you should
call the update method. This is because the draw method is never
called as a result of an EVT_PAINT event.
"""
# These are our two buffers. Just be aware that when the buffers
# are flipped, the REFERENCES are swapped. So I wouldn't want to
# try holding onto explicit references to one or the other ;)
buffer = None
backbuffer = None
def __init__(self,
parent,
ID=-1,
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.NO_FULL_REPAINT_ON_RESIZE):
wx.Panel.__init__(self,parent,ID,pos,size,style)
# Bind events
self.Bind(wx.EVT_PAINT, self.onPaint)
self.Bind(wx.EVT_SIZE, self.onSize)
# Disable background erasing (flicker-licious)
def disable_event(*pargs,**kwargs):
pass # the sauce, please
self.Bind(wx.EVT_ERASE_BACKGROUND, disable_event)
# Ensure that the buffers are setup correctly
self.onSize(None)
##
## General methods
##
def draw(self,dc):
"""
Stub: called when the canvas needs to be re-drawn.
"""
pass
def flip(self):
"""
Flips the front and back buffers.
"""
self.buffer,self.backbuffer = self.backbuffer,self.buffer
self.Refresh()
def update(self):
"""
Causes the canvas to be updated.
"""
dc = wx.MemoryDC()
dc.SelectObject(self.backbuffer)
#dc.BeginDrawing()
self.draw(dc)
#dc.EndDrawing()
self.flip()
##
## Event handlers
##
def onPaint(self, event):
# Blit the front buffer to the screen
dc = wx.BufferedPaintDC(self, self.buffer)
def onSize(self, event):
# Here we need to create a new off-screen buffer to hold
# the in-progress drawings on.
width,height = self.GetClientSize()
if width == 0:
width = 1
if height == 0:
height = 1
self.buffer = wx.Bitmap(width,height)
self.backbuffer = wx.Bitmap(width,height)
# Now update the screen
self.update()
class TestCanvas(BufferedCanvas):
def __init__(self,parent,controls, ID=-1):
self.controls = controls
self.image = None
BufferedCanvas.__init__(self,parent,ID)
def draw(self, dc):
dc.SetBackground(wx.Brush("White"))
dc.Clear()
W,H = self.GetSize()
x = int(self.controls.x_txt.GetValue())
y = int(self.controls.y_txt.GetValue())
if self.image:
y = min(y, self.y_max)
x = min(x, self.x_max)
if W>self.x_max:
x=0
if H>self.y_max:
y=0
dc.SetBrush(wx.BLUE_BRUSH)
dc.SetPen(wx.Pen('Black', 1))
for yy in range(min(H, self.y_max)):
for xx in range(min(W, self.x_max)):
try:
y_row_offset = (y+yy)*self.x_max
pixel_number = x+xx+ y_row_offset
byte_number = int(pixel_number/8)
r = 8-((pixel_number+1) % 8)
if r == 8:
r=0
pixel = self.image[byte_number]>>r & 1
if pixel:
dc.DrawPoint(xx, yy)
except IndexError:
print('x {} xx {} y {} yy {} w {} h {} x_max {} y_max {}'
.format(x, xx, y, yy, W, H, self.x_max, self.y_max))
raise
else:
dc.SetBrush(wx.BLUE_BRUSH)
dc.SetPen(wx.Pen('Red', 1))
for xx in range(W):
dc.DrawPoint(xx, 0)
dc.DrawPoint(xx, 100)
# dc.DrawRectangle(x,
# y,
# W,H)
class ControlPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.gs = wx.GridSizer(2,2,0,0)
x_lbl = wx.StaticText(self, label='X coord')
self.x_txt = wx.TextCtrl(self, value='0', style = wx.TE_PROCESS_ENTER)
y_lbl = wx.StaticText(self, label='Y coord')
self.y_txt = wx.TextCtrl(self, value='0', style = wx.TE_PROCESS_ENTER)
self.gs.Add(x_lbl, 0, wx.ALL, 1)
self.gs.Add(self.x_txt, 0, wx.ALL, 1)
self.gs.Add(y_lbl, 0, wx.ALL, 1)
self.gs.Add(self.y_txt, 0, wx.ALL, 1)
self.x_txt.Bind(wx.EVT_TEXT_ENTER, self.textEnter)
self.y_txt.Bind(wx.EVT_TEXT_ENTER, self.textEnter)
self.SetSizerAndFit(self.gs)
def textEnter(self, event):
print('textEnter')
self.canvas.update()
class TestFrame(wx.Frame):
def __init__(self,
parent=None,
ID=-1,
title="CTRL O to open image",
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self,parent,ID,title,pos,size,style)
self.splitter = wx.SplitterWindow(self)
self.controlPanel = ControlPanel(self.splitter)
self.canvas = TestCanvas(self.splitter, self.controlPanel)
self.controlPanel.canvas = self.canvas
self.splitter.SplitVertically(self.controlPanel, self.canvas)
self.splitter.SetMinimumPaneSize(30)
self.Bind(wx.EVT_CLOSE, self.onClose)
#self.Bind(wx.EVT_KEY_DOWN, self.onKeyPress)
self.Bind(wx.EVT_MENU, self.onKeyCombo)
accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('O'), self.Id)])
self.SetAcceleratorTable(accel_tbl)
#self.image_path = 'Super_Mario_Bros.pbm'
#self.open_file()
def onKeyCombo(self, event):
""""""
print("You pressed CTRL+O!")
openFileDialog = wx.FileDialog(self, "Open", "", "",
"PBM image files (*.pbm)|*.pbm",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
openFileDialog.ShowModal()
self.image_path = openFileDialog.GetPath()
print('you chose ' + self.image_path)
openFileDialog.Destroy()
self.open_file()
def open_file(self):
with wx.BusyInfo("Please wait, working..."):
with open(self.image_path, 'rb') as f:
self.canvas.image = f.read()
b = ''
i=0
meta = ''#bytearray()
def get_line():
nonlocal b, i, meta
while b!='\n':
b=self.canvas.image[i]
b=chr(b)
i+=1
meta+=b
get_line()
print(meta)
meta=''
b=''
get_line()
print(meta)
w,h = map(int, meta.split())
self.canvas.y_max = h
self.canvas.x_max = w
self.canvas.image=self.canvas.image[i:]
def onKeyPress(self, event):
keycode = event.GetKeyCode()
controlDown = event.CmdDown()
print('{} {}'.format('CTRL' if controlDown else '', keycode))
# if keycode == wx.WXK_SPACE:
# print("you pressed the spacebar!")
event.Skip()
def onClose(self,event):
self.Show(False)
self.Destroy()
def main():
app = wx.App()
frame = TestFrame()
frame.Show(True)
app.MainLoop()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment