コード例 #1
0
ファイル: HW1.py プロジェクト: ranayukirin/ImageProce_hw1
def Save_im():
    global im_choose, imtk, lb2, lb7, save_str
    im_save = Bitmap(512, 512)
    im_save.setPixel(np.uint8(im_choose))
    im_save.write(save_str)
    lb7 = tk.Label(window, text = '- Done saving bmp -',
               width=20, height=1).place(x = 362, y = 60)
コード例 #2
0
ファイル: automata.py プロジェクト: PashaWNN/education
def main():
    width = 512
    gens = 512
    seed()
    a = Automata(int(input('Введите правило: ')))
    mode = input('Режим: из одной точки p, случайное заполнение r: ')
    if mode == 'r':
        a.random()
    elif mode == 'p':
        a.cells[width // 2] = True
    else:
        print('Неправильный режим')
    b = Bitmap(width=width, height=gens)
    for gen in range(0, gens):
        for i in range(0, width):
            b.setPixel(i, gen, BLACK if a.cells[i] else WHITE)
        a.do_gen()
    b.write('file.bmp')
コード例 #3
0
class ModulenControl(PanelModules, ControlBase):
    def __init__(self, parent, remote):
        """ remote is instance of HubProtocol for communication with remote"""
        PanelModules.__init__(self, parent)
        ControlBase.__init__(self)
        self.remote = remote
        self.scaleX = 1
        self.scaleY = 1
        self.drawMode = 0
        self.hubList = hubs.HubListModel(self.scrolledWindowHubs, self)
        listHubsSizer = wx.BoxSizer(wx.VERTICAL)
        listHubsSizer.Add(self.hubList, 1, wx.ALL | wx.EXPAND, 5)
        self.scrolledWindowHubs.SetSizer(listHubsSizer)
        listHubsSizer.Fit(self.scrolledWindowHubs)

        self.fanbotList = hubs.FanbotListModel(self.scrolledWindowFanbots, self)
        listFanbotsSizer = wx.BoxSizer(wx.VERTICAL)
        listFanbotsSizer.Add(self.fanbotList, 1, wx.ALL | wx.EXPAND, 5)
        self.scrolledWindowFanbots.SetSizer(listFanbotsSizer)
        listFanbotsSizer.Fit(self.scrolledWindowFanbots)

        self.pointCurrent = wx.Point(0, 0)
        self.pointPrevious = wx.Point(0, 0)
        self.currenthub = None

        self.compressedFrame = array.array("B", [0] * 125)

        self.bitmap = Bitmap(FanbotConfig.width, FanbotConfig.height)
        self.bitmap.clear()

        for hub in self.hubList.hubs:
            self.showHub(hub)

        self.timerAnimate = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.timerAnimateHandler, self.timerAnimate)
        self.animateIdx = 0

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.timerDiscover, self.timer)
        self.timerDiscoverCount = 0

    def buttonResetDiscOnButtonClick(self, event):
        self.remote.sendCommand(HubProtocol.RESET)
        self.hubList.resetDiscovery()

    def buttonDiscoverOnButtonClick(self, event):
        self.remote.sendCommand(HubProtocol.REQUEST_ID)
        self.timer.Start(2000)
        self.timerDiscoverCount = 2
        self.sendMessage("Discover module. Even geduld aub... ")

    def timerDiscover(self, event):
        if self.timerDiscoverCount == 0:
            self.timer.Stop()

        else:
            self.timerDiscoverCount -= 1
            self.remote.sendCommand(HubProtocol.REQUEST_ID)
            self.hubList.refresh()

    def buttonClearListOnButtonClick(self, event):
        self.listModules.Clear()

    def buttonResetConfigOnButtonClick(self, event):
        if self.currenthub:
            self.resetHub(self.currenthub)
            self.remote.sendConfig(self.currenthub.idAsArray(), self.currenthub.config)

    def buttonSetConfigOnButtonClick(self, event):
        if self.currenthub:
            hub = self.currenthub
            print "buttonSetConfigOnButtonClick, currenthub: ", hub.id
            self.remote.sendConfig(hub.idAsArray(), hub.config)

    def buttonSetConfigAllOnButtonClick(self, event):
        print "buttonSetConfigAllButtonClick"
        for hub in self.hubList.hubs:
            self.remote.sendConfig(hub.idAsArray(), hub.config)
            time.sleep(0.100)

    def panelModulesCanvasOnSize(self, event):
        rect = self.panelModulesCanvas.GetRect()

        self.scaleX = rect.GetWidth() / self.bitmap.width
        self.scaleY = rect.GetHeight() / self.bitmap.height
        # print 'Scale x:y',self.scaleX,':',self.scaleY
        self.Refresh()

    def panelModulesCanvasOnPaint(self, event):
        dc = wx.PaintDC(self.panelModulesCanvas)
        dc.BeginDrawing()
        dc.SetUserScale(self.scaleX, self.scaleY)
        dc.Clear()
        dc.DrawBitmap(self.bitmap.getBitmap(), 0, 0)
        dc.EndDrawing()

    def panelModulesCanvasOnMouseEvents(self, event):
        point = None
        canvas = self.panelModulesCanvas
        if event:
            # set mouse cursor
            canvas.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            # get device context of canvas
            dc = wx.ClientDC(canvas)
            dc.SetUserScale(self.scaleX, self.scaleY)

            point = event.GetLogicalPosition(dc)
            if point.x < 0 or point.x >= FanbotConfig.width or point.y < 0 or point.y >= FanbotConfig.height:
                # print 'x,y out of bounds: ',point.x ,':',point.y
                return
            if self.checkBoxMatrix.IsChecked():
                """ set the snapto grid to horizontal 4 and vertical 6"""
                point.x /= 4
                point.x *= 4
                point.y /= 6
                point.y *= 6

            self.labelPosition.SetLabel("%s : %s" % (point.x, point.y))
            self.pointCurrent = point
            # print "mouse event X : " ,point.x , " Y: ",point.y

        if event.LeftDown():
            self.panelModulesCanvas.Refresh()
            self.pointPrevious = self.pointCurrent
            if self.checkBoxMatrix.IsChecked():
                self.matrixHubConfig(point.x, point.y)
            else:
                self.updateHubConfig(point.x, point.y)

        elif event.LeftIsDown() and not self.checkBoxMatrix.IsChecked():
            if self.pointPrevious.x == self.pointCurrent.x and self.pointPrevious.y == self.pointCurrent.y:
                return
            self.pointPrevious = self.pointCurrent
            # print "Dragging to X : " ,point.x , " Y: ",point.y
            cur = wx.StockCursor(wx.CURSOR_CROSS)
            canvas.SetCursor(cur)
            self.updateHubConfig(point.x, point.y)

    def updateHubConfig(self, x, y):
        hub = self.currenthub
        if hub:
            if hub.canAddConfigItem():
                if self.bitmap.pixelSetWhite(x, y):
                    hub.setConfig(x, y)
                    self.panelModulesCanvas.Refresh()

    def matrixHubConfig(self, x, y):
        hub = self.currenthub
        if hub:
            if hub.canAddConfigItem():
                hub.resetConfig()
                for y in range(self.pointCurrent.y, self.pointCurrent.y + 6):
                    for x in range(self.pointCurrent.x, self.pointCurrent.x + 4):
                        self.bitmap.pixelSetWhite(x, y)
                        self.currenthub.setConfig(x, y)
                        self.panelModulesCanvas.Refresh()

    def handleCommand(self, opcode, payload):
        """ Handle incoming data from remote hubs or hubsimulator"""
        print "Modulen: Received opcode: %04x -- %s" % (opcode, payload)

        id = ""
        if len(payload) >= 4:
            for i in range(4):
                id = "%02x%s" % (payload[i], id)

        if opcode == HubProtocol.ID_REPORT:
            if len(payload) != 4:
                print "Error: incorrect length from hub received"
                return
            self.sendMessage("Discovered hub: " + id)
            print "Modulen: Received ID_REPORT from %s" % (id)
            hub = self.hubList.addHub(id)
            hub.discoverd = True
            hub.responsive = True
            # self.remote.sendCommand( HubProtocol.TAG_ID,4,hub.idAsArray() ) # remove tagging, as it messes up frames
        elif opcode == HubProtocol.STATUS_REPORT:
            hub = self.currenthub
            if hub:
                hub.setFanbots(payload)
                self.fanbotList.setFanbots(hub.fanbots)
            self.labelHubId.SetLabel("Hub: " + id)

    def hubSelected(self, hub):
        """Callback function called from the hubs list control"""
        self.showHub(self.currenthub)
        print "selected hub:", hub.id
        self.currenthub = hub

        config = hub.config
        for i in range(0, len(config)):
            tuple = hub.getConfigColor(i)
            if tuple[0] >= 0:
                x = tuple[0]
                y = tuple[1]
                self.bitmap.setPixel(x, y, 0xFFFFFF)
        self.fanbotList.setFanbots(None)
        self.labelHubId.SetLabel("Hub: ")
        self.panelModulesCanvas.Refresh()
        self.remote.sendCommand(HubProtocol.REQUEST_STATUS, 4, hub.idAsArray())
        time.sleep(0.2)
        if 0 == self.sliderAnimateHub.GetValue():
            self.createHubBitmap()
            self.remote.sendFanbotFrame(self.compressedFrame)

    def fanbbotSelected(self, item):
        mappedindex = Hub.fanbotMapping[item] - 1
        print "Selected fanbot index: %d mapped onto index %d" % (item, mappedindex)
        if 0 == self.sliderAnimateHub.GetValue():
            self.createFanbotBitmap(mappedindex)
            self.remote.sendFanbotFrame(self.compressedFrame)

    def showHub(self, hub):
        """for the given hub, show the pixels in the bitmap, in the color of he hub"""
        if hub:
            config = hub.config
            for i in range(0, len(config)):
                tuple = hub.getConfigColor(i)
                if tuple[0] >= 0:
                    x = tuple[0]
                    y = tuple[1]
                    self.bitmap.setPixel(x, y, tuple[2])

    def resetHub(self, hub):
        """for the given hub, make all its pixels gray, and then reset config"""
        if hub:
            print "reset hub:", hub.id
            config = hub.config
            for i in range(0, len(config)):
                tuple = hub.getConfigColor(i)
                if tuple[0] >= 0:
                    x = tuple[0]
                    y = tuple[1]
                    self.bitmap.pixelSetGray(x, y)
            hub.resetConfig()
            self.panelModulesCanvas.Refresh()

    def sliderAnimateHubOnScroll(self, event):
        speed = self.sliderAnimateHub.GetValue()
        if speed == 0:
            self.timerAnimate.Stop()
        else:
            self.timerAnimate.Start(250 - speed * 25)

    def timerAnimateHandler(self, event):
        """  """
        hub = self.currenthub
        if hub:
            self.animateIdx += 1
            if self.animateIdx >= 24:
                self.animateIdx = 0
            self.createFanbotBitmap(Hub.fanbotMapping[self.animateIdx] - 1)
        self.remote.sendFanbotFrame(self.compressedFrame)

    def createHubBitmap(self):
        hub = self.currenthub
        maxFrameLen = len(self.compressedFrame)
        if hub:
            for i in range(maxFrameLen):
                self.compressedFrame[i] = 0
            for i in range(24):
                pixelIdx = hub.config[i]
                if pixelIdx >= 0:
                    byteIdx = pixelIdx / 8
                    if byteIdx >= maxFrameLen:
                        return
                    bitIdx = pixelIdx % 8
                    self.compressedFrame[byteIdx] |= 1 << bitIdx

    def createFanbotBitmap(self, idx):
        hub = self.currenthub
        maxFrameLen = len(self.compressedFrame)
        if hub:
            for i in range(maxFrameLen):
                self.compressedFrame[i] = 0
            if idx >= 24:
                return
            pixelIdx = hub.config[idx]
            if pixelIdx >= 0:
                byteIdx = pixelIdx / 8
                if byteIdx >= maxFrameLen:
                    return
                bitIdx = pixelIdx % 8
                self.compressedFrame[byteIdx] = 1 << bitIdx
コード例 #4
0
ファイル: julia.py プロジェクト: PashaWNN/education
			begin
				t := z;
				{z^2 + c}
				z.x := sqr(t.x) - sqr(t.y) + c.x;
				z.y := 2*t.x*t.y + c.y;
				Inc(n);
   			end;
			if n < iter then begin
                          col := n*6 mod 255;
                          PaintBox1.Canvas.Pixels[mx+x,my+y]:=RGBToColor(col,0,0);
			end;"""
size = 511
b = Bitmap(size + 1, size + 1)

b.clear()
max = 60
iter = 100
c = complex(0.11, -0.66)
Mx = My = size // 2
for y in range(-My, My + 1):
    for x in range(-Mx, Mx + 1):
        n = 0
        z = complex(x * 0.009, y * 0.009)
        while (z.real**2 + z.imag**2) < max and n < iter:
            t = z
            z = complex(pow(t, 2) + c.real, 2 * t + c.imag)
            n += 1
        if n < iter:
            col = n * 30 % 255
            b.setPixel(Mx + x, My + y, (col, 0, 0))
b.write('file.bmp')
コード例 #5
0
class DesignControl(PanelDrawIcon ):
    def __init__( self, parent):
        PanelDrawIcon.__init__( self, parent )
        print 'DesignControl constructor  '

        self.brush = '1'
        self.drawMode = 0  
        self.brushColor = 0xFFFF;
        self.scaleX = 1
        self.scaleY = 1
        self.bitmap = Bitmap(FanbotConfig.width,FanbotConfig.height)
        self.pointCurrent = wx.Point(0,0)
        self.pointStartDrag = None
        self.pointEndDrag = None
        self.mousePoint = (0,0)
        self.panelIconCanvasOnSize(None)
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.timerAnimate, self.timer)
        self.animateIdx = 0
        self.initFileList()

 
                    
    def panelIconCanvasOnPaint( self, event ):
        dc = wx.PaintDC(self.panelIconCanvas)
        dc.BeginDrawing()
        dc.SetUserScale(self.scaleX, self.scaleY)
        dc.Clear()
        dc.DrawBitmap(self.bitmap.getBitmap(),0,0)
        dc.EndDrawing()
        
     
    def panelIconCanvasOnMouseEvents( self, event ):
        
        point = None
        canvas = self.panelIconCanvas
        if event:
            # set mouse cursor
            canvas.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            # get device context of canvas
            dc= wx.ClientDC(canvas)
            dc.SetUserScale(self.scaleX, self.scaleY)

            point = event.GetLogicalPosition(dc)
            if point.x < 0 or point.x >= FanbotConfig.width or point.y < 0 or point.y >= FanbotConfig.height:
            	#print 'x,y out of bounds: ',point.x ,':',point.y    
                return
            self.pointCurrent = point    
            #print "mouse event X : " ,point.x , " Y: ",point.y

        if event.LeftDown():
           #print "mouse down X : " ,point.x , " Y: ",point.y
           # Left mouse button down, change cursor to
           # something else to denote event capture
           self.pointStartDrag = point
           cur = wx.StockCursor(wx.CURSOR_CROSS)  
           canvas.SetCursor(cur)
           self.setPixel(point.x, point.y,self.brushColor)        
           # invalidate current canvas
           self.Refresh()

            
        if event.LeftIsDown():
            self.pointDragTo = point
            #print "Dragging to X : " ,point.x , " Y: ",point.y
            cur = wx.StockCursor(wx.CURSOR_CROSS)  
            canvas.SetCursor(cur)
            if self.drawMode == 0:
                self.setPixel(point.x, point.y,self.brushColor)
            if self.drawMode == 1:
                for x in range (self.pointStartDrag.x,point.x):
                    for y in range (self.pointStartDrag.y,point.y):
                        self.setPixel(x, y,self.brushColor)
                                    
            self.panelIconCanvas.Refresh()
                 
    """ Panel drawDesign   """
    def buttonPrevOnButtonClick( self, event ):
        self.prevFrame()
        self.labelFrame.SetLabel(self.getFrameCountAsString())
    
    def buttonNextOnButtonClick( self, event ):
        self.nextFrame()
        self.labelFrame.SetLabel(self.getFrameCountAsString())
  
    def buttonAddFrameOnButtonClick( self, event ):
        self.addFrame()
        self.labelFrame.SetLabel(self.getFrameCountAsString())
        

    def buttonDeleteFrameOnButtonClick( self, event ):
        frnr = self.delFrame()
        self.labelFrame.SetLabel(self.getFrameCountAsString())

    def buttonAddOnButtonClick( self, event ):
        wx.MessageBoxCaptionStr
        dlg = wx.TextEntryDialog(
                self, 'Filename: ',
                'Enter filename', 'Python')

        dlg.SetValue("test.gif")

        if dlg.ShowModal() == wx.ID_OK:
            fn = dlg.GetValue()
            if not fn.find('.gif'):
                fn = fn + '.gif'
            full = 'data/' + fn 
            self.setFilename(full) 
            f = open(full,'w')
            f.close()
            self.saveCurrentFile()   
      
        dlg.Destroy()
        self.listIcons.Append(fn)
         
    def buttonDeleteOnButtonClick( self, event ):
        print 'buttonDeleteOnButtonClick'
        idx = self.listIcons.GetSelection()
        if idx ==  wx.NOT_FOUND:
            return;
        fn = self.listIcons.GetString(idx)
        result = wx.MessageBox('File '+ fn +  ' wissen?', 'File wissen', 
                               wx.OK | wx.CANCEL | wx.ICON_QUESTION)
        if result == wx.OK:
            os.remove('data/' + fn)
            self.listIcons.Delete(idx)
                
    
    def buttonSaveOnButtonClick( self, event ):
        self.saveCurrentFile()
    
    def listIconsOnListBox( self, event ):
        fname = event.GetString()
        print 'selected: ', fname
        self.loadFromFile("data/" + fname)
        self.labelFrame.SetLabel(self.getFrameCountAsString())
      
    
    def sliderAnimateOnScroll( self, event ):
        pos = event.GetPosition()
        self.animate(pos)
        if pos == 0:
            self.labelFrame.SetLabel(self.getFrameCountAsString())

        
        
        
        event.Skip()    
    def initFileList(self):
        for fname in os.listdir("data"):
            if ".gif" in fname:
                #print fname
                self.listIcons.Append(fname)


    def toolBrush1OnToolClicked( self, event ):
        self.brush = '1'
    
    def toolBrush4OnToolClicked( self, event ):
        self.brush = '4'
    
    def toolBrush9OnToolClicked( self, event ):
        self.brush = '9'

    
    def toolDrawLineOnToolClicked( self, event ):
        self.drawMode = 1

    def toolDrawDotOnToolClicked( self, event ):
        self.drawMode = 0
    

    def toolColorOnToolClicked( self, event ):

        dlg = wx.ColourDialog(self)
        dlg.GetColourData().SetChooseFull(True)
        if dlg.ShowModal() == wx.ID_OK:

            # If the user selected OK, then the dialog's wx.ColourData will
            # contain valid information. Fetch the data ...
            data = dlg.GetColourData()

            # ... then do something with it. The actual colour data will be
            # returned as a three-tuple (r, g, b) in this particular case.
            print 'You selected: %s\n' % str(data.GetColour().Get() )
            r,g,b = data.GetColour().Get()
            self.brushColor =   b * 0x10000 + g * 0x100 + r
        dlg.Destroy()
    
    def toolColorBlackOnToolClicked( self, event ):
        print 'colorGray'
        self.brushColor =    0x101010
    
    def toolColorWhiteOnToolClicked( self, event ):
        print 'clororWhite'
        self.brushColor =    0xC0C0C0
    
    def panelIconCanvasOnSize( self, event ):
        rect = self.panelIconCanvas.GetRect()

        self.scaleX = rect.GetWidth() / self.bitmap.width
        self.scaleY = rect.GetHeight() / self.bitmap.height
        #print 'Scale x:y',self.scaleX,':',self.scaleY
        
        self.Refresh()
        
    def loadFromFile(self,fname):
        if self.bitmap.changed:
            result = wx.MessageBox('Bitmap is aangepast. Opslaan?', 'Opslaan', 
                                   wx.OK | wx.CANCEL |wx.ICON_INFORMATION)
            if result == wx.OK:
                self.saveCurrentFile()
        self.bitmap.loadFromFile(fname)
        self.Refresh()

    def saveCurrentFile(self):
        self.bitmap.saveCurrentFile()
  
    def getFilename(self):
        return self.bitmap.filename 
    def setFilename(self,fn):
        self.bitmap.filename = fn 

    def delFrame(self):
        """delete frame at current index.  Do nothing if only one frame        """
        self.bitmap.delFrame()
        self.Refresh()

    def addFrame(self):
        """add frame after the current index.  
        """
        self.bitmap.addFrame()
        self.Refresh()

        
    def prevFrame(self):
        """Go back  to previous  frame in animated GIF. 
        """
        self.bitmap.prevFrame()
        self.Refresh()
 
    def animate(self,speed):
        if speed == 0:
            self.timer.Stop()
        else :
            self.timer.Start(1000 -speed * 100)
 
    def timerAnimate(self,event):
        self.animateIdx += 1
        if self.animateIdx >= self.bitmap.getFrameCount():
            self.animateIdx = 0
        self.bitmap.setFrameNr(self.animateIdx)  
        self.Refresh()  

            
    def getFrameCountAsString(self):
        return '%d/%d' % (self.bitmap.getFrameNr(),self.bitmap.getFrameCount() )    
        
    def nextFrame(self):
        """Advance to next frame in animated GIF. If beyond the last do nothing
        """
        self.bitmap.nextFrame()
        self.Refresh()
        
    def setPixel(self,x,y,colour):
        if self.brush =='1':
            self.bitmap.setPixel(x, y,colour)
        elif self.brush =='4':
            self.bitmap.setPixel(x, y,colour)
            self.bitmap.setPixel(x, y+1,colour)
            self.bitmap.setPixel(x+1, y,colour)
            self.bitmap.setPixel(x+1, y+1,colour)
    
        elif self.brush == '9' and x > 0 and y > 0:
            self.bitmap.setPixel(x, y,colour)
            self.bitmap.setPixel(x, y-1,colour)
            self.bitmap.setPixel(x, y+1,colour)
            self.bitmap.setPixel(x-1, y,colour)
            self.bitmap.setPixel(x-1, y-1,colour)
            self.bitmap.setPixel(x-1, y+1,colour)
            self.bitmap.setPixel(x+1, y,colour)
            self.bitmap.setPixel(x+1, y-1,colour)
            self.bitmap.setPixel(x+1, y+1,colour)