domingo, 17 de janeiro de 2016

Pyforms - Biblioteca python para desenvolvimento de aplicações GUI

Pyforms

O pyforms é uma biblioteca de desenvolvimento de aplicações GUI para o Python 2.7 e 3.
Nesta publicação vou apenas demonstrar como desenvolver uma simples aplicação. 
Para descobrir mais sobre o pyforms consulte estes links:

import pyforms
from pyforms   import BaseWidget
from pyforms.Controls  import ControlText
from pyforms.Controls  import ControlButton
from pyforms.Controls   import ControlList
from pyforms.Controls   import ControlSlider
from pyforms.Controls   import ControlPlayer

class ComputerVisionAlgorithm(BaseWidget):

    def __init__(self):
        super(ComputerVisionAlgorithm,self).__init__('Computer vision algorithm example')

        #Definition of the forms fields
        self._videofile     = ControlFile('Video')
        self._outputfile    = ControlText('Results output file')
        self._threshold     = ControlSlider('Threshold', 114, 0,255)
        self._blobsize      = ControlSlider('Minimum blob size', 100, 100,2000)
        self._player        = ControlPlayer('Player')
        self._runbutton     = ControlButton('Run')

        #Define the function that will be called when a file is selected
        self._videofile.changed     = self.__videoFileSelectionEvent
        #Define the event that will be called when the run button is processed
        self._runbutton.value       = self.__runEvent
        #Define the event called before showing the image in the player
        self._player.processFrame   = self.__processFrame

        #Define the organization of the Form Controls
        self._formset = [ 
            ('_videofile', '_outputfile'), 
            '_threshold', 
            ('_blobsize', '_runbutton'), 
            '_player'
        ]


    def __videoFileSelectionEvent(self):
        """
        When the videofile is selected instanciate the video in the player
        """
        self._player.value = self._videofile.value

    def __processFrame(self, frame):
        """
        Do some processing to the frame and return the result frame
        """
        return frame

    def __runEvent(self):
        """
        After setting the best parameters run the full algorithm
        """
        pass

if __name__ == "__main__":   pyforms.startApp( ComputerVisionAlgorithm )



Resultado:

Stop Motion | Realidade Aumentada | Cannon 1100D

  1. Junção de todas as imagens.
  2. Corte dos cantos das imagens.
  3. Imagem estabilizada.
  4. Animação a colocar na imagem.
  5. Imagem com animação.




domingo, 14 de setembro de 2014

Python: Fazer streaming de um ficheiro utilizando http post

Procurei por todo lado e não encontrei nenhum script python para fazer streaming de um ficheiro utilizando http post!

Não tive alternativa se não fazer a minha própria implementação, e aqui está:


import httplib, os, random


def htttpPost(hostname, urlpath, parameters, files={}):
 """
 streaming a file using http post
 """
 
 boundary  = "----------------------------%s" % random.getrandbits(48)
 separator = '--' + boundary + '\r\n'
 
 total_size = 0
 data = []
 for key, value in parameters.items():
  content = separator+'Content-Disposition: form-data; name="%s"\r\n\r\n%s' % (key, value)
  total_size += len(content)
  data += [ content ]

 for key, value in files.items():
  content = separator+'Content-Disposition: form-data; name="file"; filename="%s"\nContent-Type: application/octet-stream\r\n\r\n' % key
  total_size += len(content)
  total_size += os.path.getsize(value)
 total_size += len('\r\n'+separator)

 conn = httplib.HTTPConnection(hostname)
 conn.connect()
 conn.putrequest('POST', urlpath)
 conn.putheader('Content-Length', str(total_size))
 conn.putheader("Content-Type", "multipart/form-data; boundary=%s" % boundary)
 conn.endheaders()

 for msg in data: conn.send( msg )
 
 for key, value in files.items():
  infile = open(value, 'rb')
  content = separator+'Content-Disposition: form-data; name="file"; filename="%s"\nContent-Type: application/octet-stream\r\n\r\n' % key
  conn.send(content)
  while True:
   chunk = infile.read(1024)
   if not chunk: break
   conn.send(chunk)
 conn.send('\r\n'+separator)

 resp = conn.getresponse()
 return resp

domingo, 3 de fevereiro de 2013

Imaginação, uma webcam, e tempo livre...muito tempo livre

Neste post deixo-vos alguns projectos que fiz com a minha velhinha webcam...
Já nem tenho a certeza de ainda ter o código...


Motion Cube | Motion Face | Motion Game

Neste vídeo primeiro vemos um cubo que gira à passagem de um utilizador.
No segundo 43, temos uma aplicação que coloca balões de dialogo na cabeça dos utilizadores.
E no minuto 1:18 temos um jogo de Quiz em que o utilizador usa uma luva para responder às questões correctas.



Produto externo em Python

De tempos a tempos aparece um problema onde dá jeito usar um pouco de força bruta para o resolver.
Desta vez o problema foi ter um conjunto de pontos aleatórios, onde precisava de verificar se os vectores formados por eles faziam um ângulo de 90º entre si.
A forma mais rápida que eu encontrei para o fazer, foi testar todas as combinações de pontos. Funciona, mas consome muito CPU!!... por isso procurei perceber se em Python existia alguma forma de poupar-me de fazer vários loops...

Neste post vou testar as soluções de produto externo em Python que encontrei.