analitics

Pages

Sunday, July 4, 2021

Python Qt5 : Parse files and show image with QPixmap .

This tutorial is about how to create a simple script in python with a few features:
You can see I used these python packages: argparse, PIL, glob, io, PyQt5 to fulfill the issue.
The PIL python package is used to use PNG images.
The argparse python package is used to get inputs from arguments.
The glob python package is used to parse folders and files.
The io python package is used to open images:
The PyQt5 python package is used to show images on canvas:
This is the source code in python I used to parse a folder with images and show one image:
import os
import io
import sys
import glob

from PIL import Image
from PIL import UnidentifiedImageError

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel

import argparse
from pathlib import Path

parser = argparse.ArgumentParser()

parser.add_argument("files_path", type=Path, help='PATH of folder with files ')
parser.add_argument('-p','--print_files', action='store_true', 
    help='Print files from folder ')
parser.add_argument('-s','--show', action='store_true', 
    help='Show image in PyQt5 canvas!')
args = vars(parser.parse_args())

p = parser.parse_args()
print(p.files_path, type(p.files_path), p.files_path.exists())
print(p.show)
files = os.listdir(p.files_path)
file_list = []
image_list = []
bad_files_list =[]

if args['print_files']: 
    print("These are files from folder "+str(p.files_path))
    for f in file_list:
	    print(f)

images_ext = str(Path(p.files_path))+'/*.png'
print("images_ext: "+images_ext)
for filename in glob.glob(images_ext): #assuming png
    try:
        f = open(filename, 'rb')
        file = io.BytesIO(f.read())
        im = Image.open(file)
        image_list.append(filename)
        print(str(len(image_list))+" good file is"+filename)
    except Image.UnidentifiedImageError:
        bad_files_list.append(str(p.files_path)+"/"+str(filename))

for f in bad_files_list:
	print("bad file is : " + f)


if args['show']:
    value = input("Please enter the index of PNG image :\n")
    try:
        int(value)
        print("Image number select default : " + value)      
        value = int(value)
        if value &lt= len(image_list):
            value = int(value)
        else:
            print("The number image selected is greater then len of list images!")
            value = len(image_list)
    except:
        print("This is not a number, I set first image number.")
        value = 1

    class MainWindow(QMainWindow):

        def __init__(self):
            super(MainWindow, self).__init__()
            self.title = "Image Viewer"
            self.setWindowTitle(self.title)

            label = QLabel(self)
            pixmap = QPixmap(image_list[int(value)])
            label.setPixmap(pixmap)
            self.setCentralWidget(label)
            self.resize(pixmap.width(), pixmap.height())

    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
These are the output of the script:
[mythcat@desk PIL001]$ python  tool001.py 
usage: tool001.py [-h] [-p] [-s] files_path
tool001.py: error: the following arguments are required: files_path
[mythcat@desk PIL001]$ python  tool001.py ~/Pictures/
/home/mythcat/Pictures  True
False
images_ext: /home/mythcat/Pictures/*.png
1 good file is/home/mythcat/Pictures/keyboard.png
2 good file is/home/mythcat/Pictures/Fedora_The_Pirate_CaribbeanHunt.png
3 good file is/home/mythcat/Pictures/website.png
4 good file is/home/mythcat/Pictures/Screenshot from 2021-02-19 19-24-32.png
...
97 good file is/home/mythcat/Pictures/Screenshot from 2021-07-03 17-31-23.png
98 good file is/home/mythcat/Pictures/Screenshot from 2021-07-03 17-46-05.png
bad file is : /home/mythcat/Pictures//home/mythcat/Pictures/Screenshot from 2021-02-07 14-58-56.png
bad file is : /home/mythcat/Pictures//home/mythcat/Pictures/evolution_logo.png
[mythcat@desk PIL001]$ python  tool001.py ~/Pictures/ -p
/home/mythcat/Pictures  True
False
These are files from folder /home/mythcat/Pictures
images_ext: /home/mythcat/Pictures/*.png
1 good file is/home/mythcat/Pictures/keyboard.png
2 good file is/home/mythcat/Pictures/Fedora_The_Pirate_CaribbeanHunt.png
3 good file is/home/mythcat/Pictures/website.png
...
97 good file is/home/mythcat/Pictures/Screenshot from 2021-07-03 17-31-23.png
98 good file is/home/mythcat/Pictures/Screenshot from 2021-07-03 17-46-05.png
bad file is : /home/mythcat/Pictures//home/mythcat/Pictures/Screenshot from 2021-02-07 14-58-56.png
bad file is : /home/mythcat/Pictures//home/mythcat/Pictures/evolution_logo.png
[mythcat@desk PIL001]$ python  tool001.py ~/Pictures/ -s
/home/mythcat/Pictures  True
True
images_ext: /home/mythcat/Pictures/*.png
...
97 good file is/home/mythcat/Pictures/Screenshot from 2021-07-03 17-31-23.png
98 good file is/home/mythcat/Pictures/Screenshot from 2021-07-03 17-46-05.png
bad file is : /home/mythcat/Pictures//home/mythcat/Pictures/Screenshot from 2021-02-07 14-58-56.png
bad file is : /home/mythcat/Pictures//home/mythcat/Pictures/evolution_logo.png
Please enter the index of PNG image :
6
Image number select default : 6

Tuesday, June 15, 2021

Python 3.6.9 : My colab tutorials - part 014.

Here we come to the 16th notebook created with the colab utility from Google.
In this notebook, I will show you how you can view a dataset of images.
See the next image with a few of the shapes of the dataset:
You can find the full source code on my GitHub account.

Saturday, June 5, 2021

Python 3.6.9 : My colab tutorials - part 013.

In this tutorial created with the online tool google colab, we exemplified again how to access the IMDB dataset, which contains from the index point of view and what is the correspondence with the IMDB reviews, as well as how to work and create several sets of data for trains and what is the difference between them.
You can see the source code in python on this notebook.

Tuesday, June 1, 2021

Python 3.6.9 : My colab tutorials - part 012.

The purpose of this tutorial is to show the IMDB review dataset.
You can find the source code on my GitHub account here.

Thursday, May 27, 2021

Python 3.6.9 : My colab tutorials - part 011.

The purpose of this tutorial is to use the google TPU device together with Keras.
You need to set from the Edit menu and set for the notebook the device called TPU.
You can find the source code on my GitHub account here.

Tuesday, May 18, 2021

Python 3.9.1 : ABC - Abstract Base Classes - part 001.

Abstract classes are classes that contain one or more abstract methods.
By default, Python does not provide abstract classes.
Python comes with a module that provides the base for defining Abstract Base Classes (named ABC).
An abstract class can be considered as a blueprint for other classes.
By defining an abstract base class, you can define a common API for a set of subclasses.
A class that is derived from an abstract class cannot be instantiated unless all of its abstract methods are overridden.
[mythcat@desk ~]$ python3.9
Python 3.9.5 (default, May  4 2021, 00:00:00) 
[GCC 10.3.1 20210422 (Red Hat 10.3.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from abc import ABC
>>> class Test_ABC(ABC):
...     pass
... 
>>> Test_ABC.register(tuple)

>>> assert issubclass(tuple,Test_ABC)
>>> assert isinstance((), Test_ABC)
>>> class Foo:
...     def __getitem__(self, index):
...         ...
...     def __len__(self):
...         ...
...     def get_iterator(self):
...         return iter(self)
... 
>>> Test_ABC.register(Foo)
...
Let's see an example:
from abc import ABC, abstractmethod
 
class Vehicle(ABC):
    @abstractmethod
    def action(self):
        pass

class Air(Vehicle):
    # overriding abstract method
    def action(self):
        print("this flies in the air")
 
class Ground(Vehicle):
    # overriding abstract method
    def action(self):
        print("this running on the field")

class Civil(Ground):
    def action(self):
        print("Civil class - running on the field")

# Can't instantiate abstract class with abstract method action, don't use it
# abc = Vehicle()

abc = Air()
abc.action()

abc = Ground()
abc.action()

abc = Civil()
abc.action()

print( issubclass(Civil, Vehicle))
print( isinstance(Civil(), Vehicle))
This is the result:
[mythcat@desk PythonProjects]$ python3.9 ABC_001.py 
this flies in the air
this running on the field
Civil class - running on the field
True
True

Saturday, February 27, 2021

Python 2.7.18 : Kick Start Google - Boring Numbers.

Today I solved one of the problems required for solving Google Kick Start in 2020, see on my account.
Round H 2020 - Kick Start 2020 Boring Numbers (7pts, 12pts) Problem Ron read a book about boring numbers. According to the book, a positive number is called boring if all of the digits at even positions in the number are even and all of the digits at odd positions are odd. The digits are enumerated from left to right starting from 1. For example, the number 1478 is boring as the odd positions include the digits {1, 7} which are odd and even positions include the digits {4, 8} which are even. Given two numbers L and R, Ron wants to count how many numbers in the range [L, R] (L and R inclusive) are boring. Ron is unable to solve the problem, hence he needs your help.
Let's try to find the solution:
import math
print("Round H 2020 - Kick Start 2020: Detect is positive number is called boring.\n")
nr = int(input("get natural positive number: "))

all_cond = []
# detect if the number is odd or even number
def detect_odd_even(num):
  if (num % 2) == 0:  
    #print("{0} is Even number".format(num)) 
    detect = True  
  else:  
    #print("{0} is Odd number".format(num))  
    detect = False
  return detect
# check if is an boring number.
def boring_number(num):
    for p,num in enumerate(str(num),1):
        print(p,num)
        if (detect_odd_even(p) == detect_odd_even(int(num))): all_cond.append(True)
        else:
          all_cond.append(False)

# check the number is 
boring_number(nr)
# print result if the positive number is boring
if (all(all_cond) == True): print("{0} is an positive boring number".format(nr))
else:
  print("{0} is not a positive boring number".format(nr))
Let's test it:
~/mathissues$ python math_003.py 
Round H 2020 - Kick Start 2020: Detect is positive number is called boring.

get natural positive number: 345
(1, '3')
(2, '4')
(3, '5')
345 is an positive boring number
Then la last step is to test any number from range of given two numbers L and R.
The new source code is this:
import math
print("Round H 2020 - Kick Start 2020: Detect is positive number is called boring.\n")
#nr = int(input("get natural positive number: "))

all_cond = []
# detect if the number is odd or even number
def detect_odd_even(num):
  if (num % 2) == 0:  
    #print("{0} is Even number".format(num)) 
    detect = True  
  else:  
    #print("{0} is Odd number".format(num))  
    detect = False
  return detect
# check if is an boring number.
def boring_number(num):
    for p,num in enumerate(str(num),1):
        print(p,num)
        if (detect_odd_even(p) == detect_odd_even(int(num))): all_cond.append(True)
        else:
          all_cond.append(False)

# check the number is 
#boring_number(nr)
# print result if the positive number is boring

nr1 = int(input("get firt natural positive number: "))
nr2 = int(input("get firt natural positive number: "))
if nr1 < nr2:
  n1 = nr1
  n2 = nr2
else: 
  n1 = nr2
  n2 = nr1
for all_nr in range(n1,n2):
  all_cond = []
  boring_number(all_nr)
  print(all_nr)
# print result if the positive number is boring
  if (all(all_cond) == True): print("{0} is an positive boring number".format(all_nr))
  else: print("{0} is not a positive boring number".format(all_nr))
  all_cond = [] 
The final solution result to test all numbers in range given two numbers L and R can be see bellow:
~/mathissues$ python math_003.py 
Round H 2020 - Kick Start 2020: Detect is positive number is called boring.

get firt natural positive number: 11
get firt natural positive number: 16
(1, '1')
(2, '1')
11
11 is not a positive boring number
(1, '1')
(2, '2')
12
12 is an positive boring number
(1, '1')
(2, '3')
13
13 is not a positive boring number
(1, '1')
(2, '4')
14
14 is an positive boring number
(1, '1')
(2, '5')
15
15 is not a positive boring number

Thursday, February 25, 2021

Python 3.9.1 : Python and Spectator Earth.

The Spectator Earth allows you to track satellites, access their imagery, and easily build new information, based on data from this amazing orbital infrastructure.
You need just an API KEY to use it with cURL, Python, or JavaScript. 
In this tutorial, I will show you how can be used.
Login on the app.spectator.earth and get your API Key. 
Let's see some simple examples.
This first example shows you the satellite by id:
import requests

id = input("Type id sattelite: ")
satellite_id = id
url = 'https://api.spectator.earth/satellite/{satellite_id}'.format(satellite_id=satellite_id)

response = requests.get(url)
data = response.json()
print(data)
Let's see some satellite by ids:
[mythcat@desk Spectator]$ python  satellite_all.py 
Type id sattelite: 1
{'id': 1, 'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-51.88851761326367, 
70.75978200389422]}, 'properties': {'name': 'Sentinel-1A', 'norad_id': 39634, 'sensors': 
[{'type': 'SAR', 'avg_footprint_width': '3.20'}], 'open': True, 'platform': 'Sentinel-1A'}}
[mythcat@desk Spectator]$ python  satellite_all.py 
Type id sattelite: 2
{'id': 2, 'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [42.046601163641796, 
-14.660442921557335]}, 'properties': {'name': 'Sentinel-2A', 'norad_id': 40697, 'sensors': 
[{'type': 'OPTICAL', 'avg_footprint_width': '2.32'}], 'open': True, 'platform': 'Sentinel-2A'}}
[mythcat@desk Spectator]$ python  satellite_all.py 
Type id sattelite: 3
{'id': 3, 'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-91.98478583784988, 
79.45732380441011]}, 'properties': {'name': 'Sentinel-3A', 'norad_id': 41335, 'sensors': 
[{'type': 'OPTICAL', 'avg_footprint_width': '10.16'}, {'type': 'OPTICAL', 
'avg_footprint_width': '11.20'}], 'open': True, 'platform': 'Sentinel-3A'}}
[mythcat@desk Spectator]$ python  satellite_all.py 
Type id sattelite: 4
Let's see one example with satellite overpasses:
import requests
import json
api_key = input("api_key :")
bbox = '19.59,49.90,20.33,50.21'
satellites = 'Sentinel-2A,Sentinel-2B'
url = 'https://api.spectator.earth/overpass/?api_key={api_key}&bbox={bbox}&
satellites={satellites}'.format(api_key=api_key, bbox=bbox, satellites=satellites)
response = requests.get(url)
data = response.json()
print(type(data))
print(data)
You can query for overpasses of the chosen satellite over a defined area of interest and the output provides you with a satellite sensor footprint for the nearest overpass, overpass frequency in seconds, and all information available.
Query parameters for the URL variable are:
The result is this:
[mythcat@desk Spectator]$ python satellite.py 
api_key :....
...
{'frequency': 93996, 'overpasses': [{'id': 16486437, 'acquisition': True, 'date': 
'2021-02-26T09:57:00Z', 'footprint': {'type': 'Polygon', 'coordinates': 
...
footprint': {'type': 'Polygon', 'coordinates': 
...
[[[19.153675312697636, 46.847554078717884], ... 
Query parameters for the url :
  • api_key - your API key
  • bbox - area of interest bounding box list of coords (lon, lat, lon, lat);
  • satellites - which satellites to include like: (Sentinel-1A, Sentinel-1A, Sentinel-2A, Sentinel-2B, Sentinel-3A, Landsat-8) - optional;
  • days_before - a number of days before the current date for which overpasses should be computed integer optional, default=0;
  • days_after - a number of days after the current date for which overpasses should be computed integer optional, default=7;
You can see a image get from my location:

Tuesday, January 26, 2021

Python 3.6.0 : Django 3.2 alpha 1 released.

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. 

I tested it and I was satisfied with the way it works with this framework and it has many good features for the web. 
Django 3.2 is designated as a long-term support release.

Today, Django 3.2 alpha 1 is available with new features.
A good roadmap towards Django 3.2. can be found on this schedule webpage.
As with all alpha and beta packages, this is not for production use.
Django 3.2 supports Python 3.6, 3.7, 3.8, and 3.9. The next release is expected in April 2021, see:
  • January 14, 2021, Django 3.2 alpha; feature freeze;
  • February 18 Django 3.2 beta; non-release blocking bug fix freeze;
  • March 18 Django 3.2 RC 1; translation string freeze;
  • April 6 Django 3.2 final release.

Sunday, December 27, 2020

Python 3.9.1 : Testing the drawSvg python package.

The tutorial for today is about drawSvg python package.
This python package let you to create SVG images (vector drawings) and rendering them or displaying them in a Jupyter notebook.
Let's install it with pip3 tool:
[mythcat@desk ~]$ cd PythonProjects/
[mythcat@desk PythonProjects]$ pip3 install drawSvg
...
Successfully installed drawSvg-1.7.0 imageio-2.9.0
A simple source code test added to svg_001.py python script:
import drawSvg as draw

# Draw a frame of the animation
def draw_frame(t):
    #Create draw surface and add a geometric shapes ...
    out = draw.Drawing(1, 1, origin=(0,0))
    out.setRenderSize(h=460)
    out.append(draw.Rectangle(0, 0, 5, 5, fill='white'))
    y = t + 0.3
    out.append(draw.Circle(0.5, y, 0.5, fill='blue'))
    return out

with draw.animate_video('example.gif', draw_frame, duration=0.01) as anim:
    # Add each frame to the animation
    for i in range(20):
        anim.draw_frame(i/10)
You can change the source code and open the GIF animation file:
[mythcat@desk PythonProjects]$ vi svg_001.py
[mythcat@desk PythonProjects]$ python svg_001.py 
[mythcat@desk PythonProjects]$ google-chrome example.gif
The result of the source code is this:

Monday, December 21, 2020

Python 3.6.9 : Ursina python game engine - part 001 .

I wrote the tutorial a few days ago and today I completed it with a video clip ...
The official webpage comes with this intro:
Ursina makes it easier to develop games, visualizations and other kinds of software.
The concise API combined with the power of the Python programming language, makes life easier for the developer so they can focus on what they are making.

Ursina can be used on Windows and Linux
Today I tested on Fedora Linux and works great.
First, the install process is easy with pip3 tool.
[mythcat@desk ~]$ pip3 install ursina
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: ursina in ./.local/lib/python3.9/site-packages (3.2.2)
Requirement already satisfied: screeninfo in ./.local/lib/python3.9/site-packages (from ursina) (0.6.6)
Requirement already satisfied: numpy in /usr/lib64/python3.9/site-packages (from ursina) (1.19.4)
Requirement already satisfied: panda3d in ./.local/lib/python3.9/site-packages (from ursina) (1.10.7)
Requirement already satisfied: pyperclip in ./.local/lib/python3.9/site-packages (from ursina) (1.8.1)
Requirement already satisfied: pillow in /usr/lib64/python3.9/site-packages (from ursina) (7.2.0)
Let's create some examples and see how this python package works.
Create a python script file:
[mythcat@desk ~]$ cd PythonProjects/
[mythcat@desk PythonProjects]$ vi ursina_001.py
Add this simple example:
from ursina import *
# create the application
app = Ursina()
# set some data , like a cube
ground = Entity(
    model = 'cube',
    color = color.blue,
    z = -.1,
    y = -3,
    origin = (0, .5),
    scale = (50, 1, 10),
    collider = 'box'
    )
# run the application
app.run()
And the last pas, run it with python:
[mythcat@desk PythonProjects]$ python ursina_001.py 
ursina version: 3.2.2
package_folder: /home/mythcat/.local/lib/python3.9/site-packages/ursina
asset_folder: .
psd-tools not installed
which: no blender in (/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:
/home/mythcat/.composer/vendor/bin:/home/mythcat/.dotnet/tools:/var/lib/snapd/snap/bin)
blender_paths:
{}
OS: posix
screen resolution: (1280, 1024)
Known pipe types:
  glxGraphicsPipe
(all display modules loaded.)
render mode: default
no settings.py file
no settings.py file
development mode: True
application successfully started
You can read on web!:

Sunday, December 6, 2020

Python 3.6.9 : My colab tutorials - part 010.

In this tutorial created with Colab online tool I used HTML and JavaScript source code.
The tutorial is easy to understand and use it.
You can see all my examples of my GitHub repo.

Thursday, December 3, 2020

Python 3.6.9 : My colab tutorials - part 009.

I update may colab work and I add new notebooks.
You can see all of these on my GitHub account.
These are examples:
  • catafest_009.ipynb - show you how to use %% colab features;
  • catafest_010.ipynb - example with Detectron2 is Facebook AI Research's with state-of-the-art object detection algorithms;
  • catafest_011.ipynb - test a sound classification with YAMNet from a web example - not very happy with the result;