analitics

Pages

Friday, October 26, 2018

Python Qt5 : MP3 player example.

This tutorial with PyQt5 will allow us to play an MP3 file using QtMultimedia.
I used a test.mp3 file in the same folder with my python script.
This is the source script:
import sys

from PyQt5 import QtCore, QtWidgets, QtMultimedia

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    filename = 'test.mp3'
    fullpath = QtCore.QDir.current().absoluteFilePath(filename) 
    media = QtCore.QUrl.fromLocalFile(fullpath)
    content = QtMultimedia.QMediaContent(media)
    player = QtMultimedia.QMediaPlayer()
    player.setMedia(content)
    player.play()
    sys.exit(app.exec_())

Wednesday, October 24, 2018

Python Qt5 : Webcam example.

Today I come with another source code.
This example uses QtMultimedia to create use of the webcam.
The source code follows the steps from finding, set and use a webcam.
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *

import os
import sys

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.online_webcams = QCameraInfo.availableCameras()
        if not self.online_webcams:
            pass #quit
        self.exist = QCameraViewfinder()
        self.exist.show()
        self.setCentralWidget(self.exist)

        # set the default webcam.
        self.get_webcam(0)
        self.setWindowTitle("WebCam")
        self.show()

    def get_webcam(self, i):
        self.my_webcam = QCamera(self.online_webcams[i])
        self.my_webcam.setViewfinder(self.exist)
        self.my_webcam.setCaptureMode(QCamera.CaptureStillImage)
        self.my_webcam.error.connect(lambda: self.alert(self.my_webcam.errorString()))
        self.my_webcam.start()

    def alert(self, s):
        """
        This handle errors and displaying alerts.
        """
        err = QErrorMessage(self)
        err.showMessage(s)


if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setApplicationName("WebCam")

    window = MainWindow()
    app.exec_()

Tuesday, October 23, 2018

Python Qt5 : toolbar example.

This is a simple example with PyQt5 python module and python 3.6.4 version.
The example is about how to create a toolbar with PyQt5.
The base of this source code is the create a default window application.
I create a toolbar and I add an action to this toolbar.
The name of the toolbar is my_toolbar.
The action is named one_action.
This action is linked to a python function named action_one.
I add to my source code another function named alert.
This is good for debugging part to handle with errors and displaying alerts.
Let's see the source code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.status = QStatusBar()
        self.setStatusBar(self.status)
        my_toolbar = QToolBar("toolbar")
        my_toolbar.setIconSize(QSize(48, 48))
        self.addToolBar(my_toolbar)
        
        one_action = QAction(QIcon(), "Action one", self)        
        one_action.setStatusTip("Action one on toolbar")
        one_action.triggered.connect(self.action_one)
        my_toolbar.addAction(one_action)
        
        self.setWindowTitle("Window PyQt5 - 001")
        self.show()

    def action_one(self):
        print("Action one")

    def alert(self, s):
        """
        This handle errors and displaying alerts.
        """
        err = QErrorMessage(self)
        err.showMessage(s)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setApplicationName("Window PyQt5 - 001")

    window = MainWindow()
    app.exec_()

Sunday, October 21, 2018

OpenGL and OpenCV with python 2.7 - part 006.

Today I deal with a simple example about how to use your webcam like a python module.
This will allow you to make your python module for your webcam.
My reason was to make a good webcam module to work with python modules like OpenCV and OpenGL and webcam devices.
The source code is simple and has just three functions: start, _update_frame and get_current_frame.
You can make more functions into this python module named webcam.
import cv2
from threading import Thread
  
class webcam:
  
    def __init__(self):
        self.video_capture = cv2.VideoCapture(0)
        self.current_frame = self.video_capture.read()[1]
          
    # create thread for capturing images
    def start(self):
        Thread(target=self._update_frame, args=()).start()
  
    def _update_frame(self):
        while(True):
            self.current_frame = self.video_capture.read()[1]
                  
    # get the current frame
    def get_current_frame(self):
        return self.current_frame
I make also a python script to test this python module:
from webcam import webcam
import cv2
 
dir(webcam)
cam = webcam()
cam.start()
 
while True:
     
    # get image from webcam
    image = cam.get_current_frame()

The shutil python module.

The shutil module helps you to accomplish tasks, such as: copying, moving, or removing directory trees.
This python script creates a zip file in the current directory containing all contents of dir and then clears dir.

import shutil
from os import makedirs

def zip(out_fileName, dir):
shutil.make_archive(str(out_fileName), 'zip', dir)
shutil.rmtree(dir)
makedirs(dir[:-1])

The scapy python module - part 002.

This is another python tutorial about scapy python module.
The last was made on Linux and now I used Windows 10 OS.
Let's install this python module with python version 2.7.13 and pip.
C:\>cd Python27

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install scapy
Collecting scapy
  Downloading scapy-2.3.3.tgz (1.4MB)
    100% |################################| 1.4MB 736kB/s
  In the tar file c:\users\mythcat\appdata\local\temp\pip-26vi9x-unpack\scapy-2.3.3.tgz 
the member scapy-2.3.3/README is invalid: unable to resolve link inside archive
Installing collected packages: scapy
  Running setup.py install for scapy ... done
Successfully installed scapy-2.3.3
The next step is to deal with
C:\Python27\Scripts>python
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scapy
>>> from scapy import *
>>> dir(scapy)
['VERSION', '_SCAPY_PKG_DIR', '__builtins__', '__doc__', '__file__', '__name__', '__package__',
 '__path__', '_version', '_version_from_git_describe', 'base_classes', 'config', 'dadict', 'data',
 'error', 'os', 'plist', 'pton_ntop', 're', 'subprocess', 'supersocket', 'themes', 'utils', 
'with_statement']

This is not working on WINDOWS