Python | HackLAB https://www.geeks3d.com/hacklab 3D Programming, Prototyping and Gamedev with GeeXLab Tue, 16 Aug 2022 15:10:09 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 (Demo) NVIDIA NVML Library in Python 3 https://www.geeks3d.com/hacklab/20220816/demo-nvidia-nvml-library-in-python-3/ https://www.geeks3d.com/hacklab/20220816/demo-nvidia-nvml-library-in-python-3/#respond Tue, 16 Aug 2022 09:51:44 +0000 https://www.geeks3d.com/hacklab/?p=1666 Downloads Python 3 Demopack Demo: geexlab-demopack-python3/nvidia/nvml/main.xml GeeXLab Downloads Forum thread for feedbacks / bug-report How to run the demo? Download and unzip GeeXLab and the demopack where you want, launch GeeXLab and drop the demo (main.xml) in GeeXLab. This demo requires OpenGL 2.1 and Python 3.8+.   NVIDIA NVML is NVIDIA’s Management Library. NVML allows to get various informations about the graphics hardware and the … Continue reading (Demo) NVIDIA NVML Library in Python 3 »

The post (Demo) NVIDIA NVML Library in Python 3 first appeared on HackLAB.]]>

GeeXLab - Python 3 NVIDIA NVML demo



Downloads

How to run the demo?
Download and unzip GeeXLab and the demopack where you want, launch GeeXLab and drop the demo (main.xml) in GeeXLab. This demo requires OpenGL 2.1 and Python 3.8+.

 
NVIDIA NVML is NVIDIA’s Management Library. NVML allows to get various informations about the graphics hardware and the dynamic library (nvml.dll) is shipped with NVIDIA graphics drivers. Here is a more detailed description:

NVML is a C-based API for monitoring and managing various states of the NVIDIA GPU devices. It provides a direct access to the queries and commands exposed via nvidia-smi. The runtime version of NVML ships with the NVIDIA display driver, and the SDK provides the appropriate header, stub libraries and sample applications. Each new version of NVML is backwards compatible and is intended to be a platform for building 3rd party applications.

Source: NVIDIA Management Library (NVML).

NVML is also available for Python 3 via the nvidia-ml-py package.
The installation of nvidia-ml-py is simple, just type the following command in a terminal:

pip install nvidia-ml-py

Based on the example provided by NVIDIA, I coded a small GeeXLab demo that does basic GPU monitoring (clock speeds, temperature, fan speed) of your NVIDIA GPUs. The demo is available in the Python 3 demopack: geexlab-demopack-python3/nvidia/nvml/main.xml

Here are the code snippets (INIT and FRAME scripts):

INIT script:

#-------------------------------------------------------------------
# NVIDIA NVML
#-------------------------------------------------------------------

# Python Bindings for the NVIDIA Management Library
# https://pypi.org/project/nvidia-ml-py/
# pip install nvidia-ml-py
from pynvml import *

def GpuMonitoring():

    strResult = ''

    nvmlInit()

    strResult += '  driver version: ' + str(nvmlSystemGetDriverVersion()) + '\n'

    deviceCount = nvmlDeviceGetCount()

    for i in range(0, deviceCount):
        h = nvmlDeviceGetHandleByIndex(i)

        gpu_name = nvmlDeviceGetName(h)
        strResult += '\n  GPU: ' + gpu_name + '\n'

        gpu_cores = nvmlDeviceGetNumGpuCores(h)
        strResult += '  - CUDA cores: %d\n' % gpu_cores

        gpu_core_clock = nvmlDeviceGetMaxClockInfo(h, NVML_CLOCK_GRAPHICS)
        strResult += '  - core clock: ' + str(gpu_core_clock) + ' MHz\n'
        gpu_mem_clock = nvmlDeviceGetMaxClockInfo(h, NVML_CLOCK_MEM)
        strResult += '  - mem clock: ' + str(gpu_mem_clock) + ' MHz\n'

        gpu_temp = nvmlDeviceGetTemperature(h, NVML_TEMPERATURE_GPU)
        strResult += '  - temperature: ' + str(gpu_temp) + '°C\n'

        num_fans = nvmlDeviceGetNumFans(h)
        for f in range(0, num_fans):
            fan_speed = nvmlDeviceGetFanSpeed_v2(h, f)
            strResult += '  - fan speed ' + str(f) + ': ' + str(fan_speed) + '%%\n'


    nvmlShutdown()

    return strResult


nv_gpu_monitoring_str = ""

FRAME script:

imgui_frame_begin()
gh_imgui.set_color(IMGUI_WINDOW_BG_COLOR, 0.1, 0.1, 0.1, 0.6)
gh_imgui.set_color(IMGUI_TEXT_COLOR, 1.0, 1.0, 1.0, 1.0)

is_open = imgui_window_begin_pos_size_always("Control panel", winW, winH, 0, 0)
if (is_open == 1):

  win_hovered = gh_imgui.is_window_hovered()

  gh_imgui.set_color(IMGUI_TEXT_COLOR, 1.0, 1.0, 0.0, 1.0)
  gh_imgui.text("Python version: " + sys.version)

  gh_imgui.set_color(IMGUI_TEXT_COLOR, 1.0, 1.0, 1.0, 1.0)
  gh_imgui.spacing()
  gh_imgui.spacing()
  gh_imgui.text("NVIDIA NVMLtest")

  gh_imgui.spacing()
  gh_imgui.spacing()

  if (gh_imgui.button('GPU monitoring', 180, 30) == 1):
    nv_gpu_monitoring_str = GpuMonitoring()

  gh_imgui.text_wrapped(nv_gpu_monitoring_str)

  gh_imgui.spacing()
  gh_imgui.spacing()

imgui_window_end()
imgui_frame_end()

The NVML python library is shipped with GeeXLab in the python3 folder.

The post (Demo) NVIDIA NVML Library in Python 3 first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20220816/demo-nvidia-nvml-library-in-python-3/feed/ 0
Simple Text to Speech Demo in Python 3 (with pyttsx3) https://www.geeks3d.com/hacklab/20220630/simple-text-to-speech-demo-in-python-3-with-pyttsx3/ https://www.geeks3d.com/hacklab/20220630/simple-text-to-speech-demo-in-python-3-with-pyttsx3/#respond Thu, 30 Jun 2022 14:48:56 +0000 https://www.geeks3d.com/hacklab/?p=1663 Downloads Python 3 Demopack Demo: geexlab-demopack-python3/speech/01-text-2-speech/main.xml GeeXLab Downloads Forum thread for feedbacks / bug-report How to run the demo? Download and unzip GeeXLab and the demopack where you want, launch GeeXLab and drop the demo (main.xml) in GeeXLab. This demo requires OpenGL 2.1 and Python 3.8+.   pyttsx3 is a text to speech conversion library for Python 3. This library does not require an internet … Continue reading Simple Text to Speech Demo in Python 3 (with pyttsx3) »

The post Simple Text to Speech Demo in Python 3 (with pyttsx3) first appeared on HackLAB.]]>

Text to Speech pyttsx3



Downloads

How to run the demo?
Download and unzip GeeXLab and the demopack where you want, launch GeeXLab and drop the demo (main.xml) in GeeXLab. This demo requires OpenGL 2.1 and Python 3.8+.

 
pyttsx3 is a text to speech conversion library for Python 3. This library does not require an internet connection, that’s good, GeeXLab loves offline libs!

pyttsx3 is shipped with GeeXLab 0.47.2 in the python3_8/Lib/site-packages/ folder. If you want to play with pyttsx3 in no time, just grab the latest GeeXLab + the demopack. Now, if you want to install pyttsx3, open a terminal and type:

pip install pyttsx3

Let’s see how to use pyttsx3 to hear more or less any speech from a string. Here is a simple example that import the pyttsx3 library, initializes it and play a text:

import pyttsx3 as t2s
t2s_engine = t2s.init()
tex = "The quick brown fox jumped over the lazy dog."
t2s_engine.say(text)
t2s_engine.runAndWait()

pyttsx3 offers the possibility to change the rate (number of words per minute), the volume, the voice and even the language:

rate = t2s_engine.getProperty('rate')
t2s_engine.setProperty('rate', rate)

volume = t2s_engine.getProperty('volume')
t2s_engine.setProperty('volume ', volume )

voices = t2s_engine.getProperty('voices')    
t2s_engine.setProperty('voice', voices[0].id)

I prepared a GeeXLab demo that allows you to type a short text and change the rate:


GeeXLab demo: Text to Speech with pyttsx3

This demo is available in the Python 3 demopack in the geexlab-demopack-python3/speech/01-text-2-speech/ folder.

Remark: the runAndWait() function blocks the demo. If the text is short that should be ok but for longer texts that can be a problem. One solution would be to run the text to speech conversion in a separate thread using a ZOMBIE script and shared variables or shared memory.

The post Simple Text to Speech Demo in Python 3 (with pyttsx3) first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20220630/simple-text-to-speech-demo-in-python-3-with-pyttsx3/feed/ 0
EU Covid-19 Vaccine Certificate (Health Pass) QR Code Reader in Python 3 https://www.geeks3d.com/hacklab/20210914/eu-covid-19-vaccine-certificate-health-pass-qr-code-reader-in-python-3/ https://www.geeks3d.com/hacklab/20210914/eu-covid-19-vaccine-certificate-health-pass-qr-code-reader-in-python-3/#comments Tue, 14 Sep 2021 16:31:38 +0000 https://www.geeks3d.com/hacklab/?p=1614 Downloads Python 3 Demopack Demo: geexlab-demopack-python3/qr-code/eu_health_pass_qrcode_reader/ GeeXLab full with Python3 (win64) How to run the demo? Download and unzip GeeXLab where you want, launch GeeXLab and drop the demo (main.xml) in GeeXLab. The full version of GeeXLab for Windows is recommended for this demo. The EU health pass (or Covid-19 vaccine certificate) is a document that contains some information about you (essentially your name and … Continue reading EU Covid-19 Vaccine Certificate (Health Pass) QR Code Reader in Python 3 »

The post EU Covid-19 Vaccine Certificate (Health Pass) QR Code Reader in Python 3 first appeared on HackLAB.]]>

GeeXLab - Health Pass / Covid-19 vaccine certificate QR Code Reader in Python 3



Downloads

How to run the demo?
Download and unzip GeeXLab where you want, launch GeeXLab and drop the demo (main.xml) in GeeXLab. The full version of GeeXLab for Windows is recommended for this demo.

The EU health pass (or Covid-19 vaccine certificate) is a document that contains some information about you (essentially your name and date of birth) as well as your current vaccine status (number of doses) and a big QR code that gathers all data. Here is a small demo coded in Python 3 that scans the QR code of the EU vaccine certificate, decodes it and shows you the data hidden behind this QR code.

The demo works on Windows only because of the built-in webcam functions I used for scanning QR codes. If necessary, the demo can be updated later to bypass the webcam and scan the image of a QR code you dropped in. You will be able then to run the demo on Linux too.

Moreover, the full GeeXLab for Windows contains all Python3 packages required by the demo. Just download the full version of GeeXLab, unzip it, run GeeXLab and drop the QR code demo in GeeXLab. A serious webcam is also required. A webcam that can do a clear focus on very close objects like your health pass QR code (on your mobile phone or on paper). Some tries (on the button SCAN a QR Code) will be likely necessary to read the QR code.

The core of the QR code decoding step has been adapted from this source and can be summed up to this:

– the QR code is a string starting with HC1:
– the string following HC1: is base45 encoded.
– the decoded base45 string leads to zlib-compressed data.
– the decompression leads to a CBOR Web Token structure.

To decode the QR code, you need the following Python 3 packages:
– base45
– cbor2
– zlib
– pprint

base45 and cbor2 packages be installed using pip:

pip install base45
pip install cbor2

base45 and cbor2 are already shipped with the full version of GeeXLab so don’t worry about installing them.

zlib and pprint are shipped with Python 3.

Here is the decoding function of the demo you can find in the frame.py file:

def DecodeHealthPass(payload):
  # The HC1: prefix nust be removed before decoding.
  s = payload.replace("HC1:", "")

  # decode Base45
  b45payload = base45.b45decode(s)

  # decompress using zlib
  cbordata = zlib.decompress(b45payload)
  
  # load the CBOR structure
  decoded = cbor2.loads(cbordata)
  decoded_qrcode = cbor2.loads(decoded.value[2])

  # prepare the CBOR structure in a readable way (newlines are added). 
  decoded_qrcode_str = pprint.pformat(decoded_qrcode)
  return decoded_qrcode_str

 
The demo:
GeeXLab - Health Pass / Covid-19 vaccine certificate QR Code Reader in Python 3

 
Here are the two steps to display the decoded QR code:

1/ click on SCAN a QR Code
This first step will show you the content (payload) of the QR code that must start with HC1: to be a valid health pass. You can now copy the payload to the clipboard if you need it.

2/ click on the Show decoded health pass button
This second step will decode the payload and display it in a small window. You can also copy to the clipboard the decoded health pass.

The decoded health pass contains information about the number of doses, the type of vaccin and its manufacturer. Here is a little help to decrypt these fields:

Field: ci --> "Unique Certificate Identifier, UVCI"
Field: co --> "Country of Test"
Field: is --> "Certificate Issuer"

Field: dob --> "Date of Birth, ISO 8601"

Field: dn --> "dose number"
Field: sd --> "Number of doses"

Field: mp  (medicinal product)
  EU/1/20/1528 --> Comirnaty
  EU/1/20/1507 --> COVID-19 Vaccine Moderna
  EU/1/21/1529 --> Vaxzevria
  EU/1/20/1525 --> COVID-19 Vaccine Janssen
 
Field: ma (vaccine manufacturer)
  ORG-100030215 --> Biontech Manufacturing GmbH
  ORG-100001699 --> AstraZeneca AB
  ORG-100001417 --> Janssen-Cilag International
  ORG-100031184 --> Moderna Biotech Spain S.L.
  ORG-100006270 --> Curevac AG

I added a PDF file in the demo folder that contains the specifications of the EU Covid-19 vaccine certificate.

The post EU Covid-19 Vaccine Certificate (Health Pass) QR Code Reader in Python 3 first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20210914/eu-covid-19-vaccine-certificate-health-pass-qr-code-reader-in-python-3/feed/ 2
How to Check if a Directory Exists in Lua (and in Python) https://www.geeks3d.com/hacklab/20210901/how-to-check-if-a-directory-exists-in-lua-and-in-python/ https://www.geeks3d.com/hacklab/20210901/how-to-check-if-a-directory-exists-in-lua-and-in-python/#respond Wed, 01 Sep 2021 16:14:24 +0000 https://www.geeks3d.com/hacklab/?p=1607   Checking if a directory exists in pure Lua is actually not an easy thing. Lua does not have the functions to get information about the file system and directories. You can test if a particular file exists in a folder by trying to open it (but the test can fail even if the folder exists…). One way to properly check if a directory exists … Continue reading How to Check if a Directory Exists in Lua (and in Python) »

The post How to Check if a Directory Exists in Lua (and in Python) first appeared on HackLAB.]]>

Lua language logo

 
Checking if a directory exists in pure Lua is actually not an easy thing. Lua does not have the functions to get information about the file system and directories. You can test if a particular file exists in a folder by trying to open it (but the test can fail even if the folder exists…).

One way to properly check if a directory exists is to use the LFS library. The LFS (LuaFileSystem) library works on Unix and Windows and offers functions to access the underlying directory structure and file attributes. With LFS, we can easily check if a folder exists:

function dir_exists_v1(path)
  if (lfs.attributes(path, "mode") == "directory") then
    return true
  end
  return false
end

The LFS library is available in GeeXLab. Just use the lfs library name in your Lua scripts.

In the startup demo of GeeXLab, the dir_exists() function based on LFS is used to check if the demos/ folder exists (in frame.lua) in order to display the Demos folder button:

local app_dir = gh_utils.get_app_dir()
local demos_dir = app_dir .. "/demos/"
if (dir_exists_v1(demos_dir)) then
  ...
end

 
Another way to check the existence of a directory is to use the rename function of Lua’s os library: os.rename() (based on this stackoverflow reply). Here is the dir_exists() function with os.rename():

function file_exists_v2(file)
  -- some error codes:
  -- 13 : EACCES - Permission denied
  -- 17 : EEXIST - File exists
  -- 20	: ENOTDIR - Not a directory
  -- 21	: EISDIR - Is a directory
  --
  local isok, errstr, errcode = os.rename(file, file)
  if isok == nil then
     if errcode == 13 then 
        -- Permission denied, but it exists
        return true
     end
     return false
  end
  return true
end

function dir_exists_v2(path)
  return file_exists(path .. "/")
end

This function dir_exists_v2() works fine but is slower than dir_exists_v1().

 
And just for fun, here is the Python version of dir_exists() 😀 😀

def dir_exists(path):
  return os.path.isdir(path)

More on os.path here.

The post How to Check if a Directory Exists in Lua (and in Python) first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20210901/how-to-check-if-a-directory-exists-in-lua-and-in-python/feed/ 0
GeeXLab and Python 3 on Linux https://www.geeks3d.com/hacklab/20200717/geexlab-and-python-3-on-linux/ https://www.geeks3d.com/hacklab/20200717/geexlab-and-python-3-on-linux/#respond Fri, 17 Jul 2020 14:31:58 +0000 https://www.geeks3d.com/hacklab/?p=1545 Here is a short post about how to use the Python 3 plugin on Linux. Depending on the Linux distribution / version, you can have Python 3.5, Python 3.6 or Python 3.8. Each version of Python has its own shared object file stored in /usr/lib/x86_x64-linux-gnu/ . For example with Linux Mint you have: – Python 3.5 with Linux Mint 18.3 (/usr/lib/x86_x64-linux-gnu/libpython3.5m.so.1.0) – Python 3.6 with … Continue reading GeeXLab and Python 3 on Linux »

The post GeeXLab and Python 3 on Linux first appeared on HackLAB.]]>

Python logo

Here is a short post about how to use the Python 3 plugin on Linux. Depending on the Linux distribution / version, you can have Python 3.5, Python 3.6 or Python 3.8. Each version of Python has its own shared object file stored in /usr/lib/x86_x64-linux-gnu/ . For example with Linux Mint you have:

– Python 3.5 with Linux Mint 18.3 (/usr/lib/x86_x64-linux-gnu/libpython3.5m.so.1.0)
– Python 3.6 with Linux Mint 19.3 (/usr/lib/x86_x64-linux-gnu/libpython3.6m.so.1.0)
– Python 3.8 with Linux Mint 20.0 (/usr/lib/x86_x64-linux-gnu/libpython3.8.so.1.0)

GeeXLab is compiled on Linux Mint 18.3 to keep the compatibility with the GLIBC 2.23. And the Python 3 plugin (stored in GeeXLab/dylibs/plugin_gxl_python3_x64.so) is linked with libpython3.5m.so.1.0. On Mint 18.3, the Python 3 plugin works fine. But on the latest Mint 20, it does not work anymore because libpython3.5m.so.1.0 is not found (which is normal). So a quick solution is to add a symbolic link pointing to the real Python lib in the plugins folder of GeeXLab. For example, on Mint 20, we can create a symlink called libpython3.5m.so.1.0 with (open a terminal in GeeXLab folder):

ln -s /usr/lib/x86_64-linux-gnu/libpython3.8.so.1.0 dylibs/libpython3.5m.so.1.0

I added in GeeXLab folder three scripts to update the symbolic link depending on your version of Linux / Python 3:
– python3_plugin_update_symlink_for_python35.sh
– python3_plugin_update_symlink_for_python36.sh
– python3_plugin_update_symlink_for_python38.sh

All scripts will create a symbolic link called libpython3.5m.so.1.0 in the plugins folder of GeeXLab that will make plugin_gxl_python3_x64.so happy!

The post GeeXLab and Python 3 on Linux first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20200717/geexlab-and-python-3-on-linux/feed/ 0
(Demo) How to Read Up-to-Date COVID-19 Data in Python 3 (Updated: 2021.09.14) https://www.geeks3d.com/hacklab/20200409/demo-how-to-read-up-to-date-covid-19-data-in-python-3/ https://www.geeks3d.com/hacklab/20200409/demo-how-to-read-up-to-date-covid-19-data-in-python-3/#respond Thu, 09 Apr 2020 18:05:32 +0000 https://www.geeks3d.com/hacklab/?p=1509 Downloads Python 3 Demopack Download Demo: geexlab-demopack-python3/general/03-covid19/main.xml GeeXLab Downloads Forum thread (EN)   If you wonder how to access to up-to-date data about new Coronavirus (COVID-19 or better, SARS-CoV-2 which is the official codename) cases, I found this simple to use Python package: COVID19Py (the github repository is available HERE). To install it, run the following command in a terminal (the pip executable must be … Continue reading (Demo) How to Read Up-to-Date COVID-19 Data in Python 3 (Updated: 2021.09.14) »

The post (Demo) How to Read Up-to-Date COVID-19 Data in Python 3 (Updated: 2021.09.14) first appeared on HackLAB.]]>

GeeXLab demo - How to Read Up-to-Date COVID-19 Data in Python 3



Downloads

 
If you wonder how to access to up-to-date data about new Coronavirus (COVID-19 or better, SARS-CoV-2 which is the official codename) cases, I found this simple to use Python package: COVID19Py (the github repository is available HERE).

To install it, run the following command in a terminal (the pip executable must be in the bin search path):

pip install COVID19Py

 
Alternatively, you can open a terminal in the C:\Users\USERNAME\AppData\Local\Programs\Python\Python38\Scripts\ folder where the pip executable is stored.

Once installed, this tiny lib is really easy to use. The following code snippet shows how to read all important data in few Python lines:

import COVID19Py

covid19_jhu = COVID19Py.COVID19(data_source="jhu")
latest_jhu = covid19_jhu.getLatest()
locations_ALL = covid19_jhu.getLocations(rank_by='confirmed')

 
The COVID-19 cases data is read from the Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE).

getLatest() returns the following dictionary:

{
'confirmed': 1511104, 
'deaths': 88338, 
'recovered': 0
}

 
getLocations() returns a big list of dictionaries, one dictionary for each location. Currently, 263 locations are returned by getLocations().

Here is the first entry (a dictionary) of the location list (I sorted by confirmed cases, that’s why the US are in top position…):

{
'id': 225, 
'country': 'US', 
'country_code': 'US', 
'country_population': 310232863, 
'province': '', 
'last_updated': '2020-04-09T16:25:21.803522Z', 
'coordinates': {'latitude': '37.0902', 'longitude': '-95.7129'}, 
'latest': {'confirmed': 429052, 'deaths': 14695, 'recovered': 0}
}

 
I coded a demo with GeeXLab that displays all COVID-19 cases data by location. COVID-19 confirmed cases can be visualized in 2D or 3D.

The demo requires the latest GeeXLab 0.30.0 (few bugs have been fixed in the gh_imgui library in the Python plugin).

Download the Python 3 demopack and load the geexlab-demopack-python3/general/03-covid19/main.xml demo in GeeXLab. GeeXLab 0.30+ for Windows comes with the COVID19Py package so you can directly run the demo.

2D view:
GeeXLab demo - How to Read Up-to-Date COVID-19 Data in Python 3

 
3D view:
GeeXLab demo - How to Read Up-to-Date COVID-19 Data in Python 3

 
This demo can be improved by storing COVID-19 data in a SQLite3 database and doing some interesting stats (like changes between days).

 

Update (2020.04.12): 2D mode: XBar and YBar

YBar:
GeeXLab demo - How to Read Up-to-Date COVID-19 Data in Python 3

XBar:
GeeXLab demo - How to Read Up-to-Date COVID-19 Data in Python 3

 

Update (2020.04.17): 2D mode: YBar with ImGui

YBar using ImGui progress bar
gh_imgui.progress_bar() function is used to represent confirmed cases. This solution is simpler to code because text alignment on the progress bar is handled by ImGui.

GeeXLab demo - How to Read Up-to-Date COVID-19 Data in Python 3

 

Update (2021.09.14): graph scaling

Since the first version of the demo, Covid19 cases have exploded. Here is a new version of the demo with a scaling factor you can adjust to display properly the graph bars.

GeeXLab demo - How to Read Up-to-Date COVID-19 Data in Python 3

The post (Demo) How to Read Up-to-Date COVID-19 Data in Python 3 (Updated: 2021.09.14) first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20200409/demo-how-to-read-up-to-date-covid-19-data-in-python-3/feed/ 0
Python 3 and OpenCV Part 4: Face Detection (Webcam or Static Image) https://www.geeks3d.com/hacklab/20200310/python-3-and-opencv-part-4-face-detection-webcam-or-static-image/ https://www.geeks3d.com/hacklab/20200310/python-3-and-opencv-part-4-face-detection-webcam-or-static-image/#respond Tue, 10 Mar 2020 13:34:53 +0000 https://www.geeks3d.com/hacklab/?p=1501 Downloads: Python 3 Demopack Download Demo: geexlab-demopack-python3/opencv/04-webcam-face-detection/main.xml GeeXLab Downloads Forum thread (EN) For the fourth and last article (previous articles are here, here and here), we’re going to look at face detection using OpenCV. So far, the OpenCV functions we used (image reading, webcam output) are basic functions we find in many softwares inlcuding GeeXLab. What makes OpenCV interesting is the availability of some computer … Continue reading Python 3 and OpenCV Part 4: Face Detection (Webcam or Static Image) »

The post Python 3 and OpenCV Part 4: Face Detection (Webcam or Static Image) first appeared on HackLAB.]]>

GeeXLab - Python 3 - Webcam - face detection with OpenCV


Downloads:


For the fourth and last article (previous articles are here, here and here), we’re going to look at face detection using OpenCV. So far, the OpenCV functions we used (image reading, webcam output) are basic functions we find in many softwares inlcuding GeeXLab. What makes OpenCV interesting is the availability of some computer vision algorithms such as face detection (or face recognition).

The face detection method used in the demo is based on the Haar Cascades. If, like me, you are not an expert of Haar cascades, here is what you need to know:

Object Detection using Haar feature-based cascade classifiers is an effective method proposed by Paul Viola and Michael Jones in the 2001 paper, “Rapid Object Detection using a Boosted Cascade of Simple Features”. It is a machine learning based approach in which a cascade function is trained from a lot of positive images (images of faces) and negative images (images without faces). It is then used to detect objects in other images.

More about Haar cascades can be found HERE.

OpenCV comes with pre-trained classifiers for faces and eyes we can use in our demo. These pre-trained classifiers are XML files stored in opencv/data/haarcascades/ folder. In the demo, the classifiers are stored in the demo/data/ folder:

– data/haarcascade_frontalface_default.xml
– data/haarcascade_eye.xml
– data/haarcascade_eye_tree_eyeglasses.xml

haarcascade_eye_tree_eyeglasses.xml is an eye detector with better handling of eyeglasses.

Once the classifiers (one classifier for faces, one for eyes) are initialized with XML files, they are used in detectMultiScale() function, that performs the detection.

Let see how to initialize the face and eyes classifiers and how to detect faces and eyes on a static image:

import cv2

demo_dir = gh_utils.get_demo_dir() 		
image = cv2.imread(demo_dir + 'data/pexels-people-03.jpg', cv2.IMREAD_COLOR)

# Parameter specifying how much the image size is reduced at each image scale.
fd_scaleFactor  = 1.1 

# Parameter specifying how many neighbors each candidate rectangle should have to retain it.
fd_minNeighbors  = 3 

# Initializes classifiers
face_cascade = cv2.CascadeClassifier(demo_dir + 'data/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(demo_dir + 'data/haarcascade_eye_tree_eyeglasses.xml')

# detectMultiScale requires an CV_U8 image (gray).
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detects objects of different sizes in the input image. 
# The detected objects are returned as a list of rectangles.
image_faces = face_cascade.detectMultiScale(gray_image, fd_scaleFactor, fd_minNeighbors, minSize=(80, 80))

# detect eyes for each face.
for (x,y,w,h) in image_faces:
  roi_gray = gray_image[y:y+h, x:x+w]
  eyes = eye_cascade.detectMultiScale(roi_gray)
  for (ex,ey,ew,eh) in eyes:
    e = (x+ex, y+ey, ew, eh)
    image_eyes.append(e)

image_faces is a list of rectangles for all faces. image_eyes is a list of lists: list of all face eyes lists (for each face, there is a list of eyes rectangles).



In the FRAME script, faces and eyes rectangles can be rendered as follows for the static image (face and eyes detection is done once for a static image):

num_faces_detected = len(image_faces)
if (num_faces_detected > 0):
  gh_renderer.set_line_width(4.0)
  gh_gpu_program.bind(color_prog)

  # Face rectangles ---------------------
  #
  for (x,y,w,h) in image_faces:
    gh_gpu_program.uniform4f(color_prog, "color", 0.2, 0.5, 1.0, 1)
    draw_rectangle(x-texture_width/2, texture_height/2-y, w, h) 

    if (enable_eyes_detection == 1):
      num_eyes_detected = len(webcam_eyes)
      gh_gpu_program.uniform4f(color_prog, "color", 0, 1, 0, 1)

  # Eye rectangles ---------------------
  #
  for e in image_eyes:
    draw_rectangle(e[0]-texture_width/2, texture_height/2-e[1], e[2], e[3]) 

  gh_renderer.set_line_width(1.0)

 
For a dynamic image like the webcam, faces and eyes detection works in a similar way. The only difference is that detection is launched for every new webcam image.

 
I prepared a demo that shows faces + eyes detection on a static image and on the webcam output. I also added the possibility to add a hat on detected faces…

Remark: on my system, the demo takes more than 10 seconds to start. The guilty is the webcam initialization step (OpenCV)…

GeeXLab - Python 3 - Webcam - face detection with OpenCV

 
The OpenCV face detector works also with masks:

GeeXLab - Python 3 - Webcam - face detection with OpenCV

The post Python 3 and OpenCV Part 4: Face Detection (Webcam or Static Image) first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20200310/python-3-and-opencv-part-4-face-detection-webcam-or-static-image/feed/ 0
Python 3 and OpenCV Part 3: How to Read the Webcam with OpenCV (cv2) https://www.geeks3d.com/hacklab/20200308/python-3-and-opencv-part-3-how-to-read-the-webcam-with-opencv-cv2/ https://www.geeks3d.com/hacklab/20200308/python-3-and-opencv-part-3-how-to-read-the-webcam-with-opencv-cv2/#comments Sun, 08 Mar 2020 10:36:57 +0000 https://www.geeks3d.com/hacklab/?p=1500 Downloads: Python 3 Demopack Download Demo: geexlab-python3-demopack/opencv/03-webcam/main.xml GeeXLab Downloads Forum thread (EN) For this third tutorial (part 1, part 2) about OpenCV in Python 3, we’re going to look at how to read the webcam output. OpenCV has an object for video capturing from video files, image sequences or cameras: VideoCapture. Let’s see how to create a VideoCapture object and use it to grab a … Continue reading Python 3 and OpenCV Part 3: How to Read the Webcam with OpenCV (cv2) »

The post Python 3 and OpenCV Part 3: How to Read the Webcam with OpenCV (cv2) first appeared on HackLAB.]]>

GeeXLab - Python 3 - Webcam video capture with OpenCV


Downloads:


For this third tutorial (part 1, part 2) about OpenCV in Python 3, we’re going to look at how to read the webcam output.

OpenCV has an object for video capturing from video files, image sequences or cameras: VideoCapture. Let’s see how to create a VideoCapture object and use it to grab a frame from the webcam.

INIT script:

import cv2

video_capture_device_index = 0
webcam = cv2.VideoCapture(video_capture_device_index)

ret, video_frame = webcam.read()

 
That’s all.

If you have several webcams, you can specify the webcam by its index. Most users have only one webcam, therefore the video_capture_device_index is set to 0.

The read() grabs, decodes and returns a video frame. The video_frame is an NumPy array and, thanks to the part 2 we know how to convert it in a GeeXLab texture and how to display it. But before creating the texture, we need to know the size of the video frame. One way to do it is to read the video capture properties:

frame_width = int(round(webcam.get(cv2.CAP_PROP_FRAME_WIDTH)))
frame_height = int(round(webcam.get(cv2.CAP_PROP_FRAME_HEIGHT)))

 
We can now create the texture and update it with the video frame:

PF_U8_RGB = 1
PF_U8_BGR = 2
PF_U8_RGBA = 3

# BGR U8 is the default pixel format of OpenCV images.
# We create an empty texture
frame_texture = gh_texture.create_2d(frame_width, frame_height, PF_U8_BGR)

# and we update the texture pixmap with the OpenCV image.
gh_texture.update_gpu_memory_from_numpy_img(frame_texture, video_frame)

 
In the FRAME script, we can update the the texture every 50 ms and display it every frame:

dt = gh_utils.get_time_step()

gh_texture.bind(frame_texture, 0)

video_dt = video_dt + dt
if (video_dt > 0.05):
  video_dt = 0
  ret, frame = webcam.read()
  gh_texture.update_gpu_memory_from_numpy_img(frame_texture, frame)

gh_camera.bind(camera_ortho)
gh_gpu_program.bind(texture_prog)
gh_object.render(quad)

 
Here is the demo:
GeeXLab - Python 3 - Webcam video capture with OpenCV

 
Keep in mind that frame_texture is a regular 2D texture you can map on any object (torus, sphere, …):

Webcam output mapped on a sphere:
GeeXLab - Python 3 - Webcam video capture with OpenCV

 
Webcam output mapped on a donut:
GeeXLab - Python 3 - Webcam video capture with OpenCV

 
The demo shows how to save a file with OpenCV too. At the end of the FRAME script there is the following piece of code:

if (gh_imgui.button("Screenshot", 100, 20) == 1):
  demo_dir = gh_utils.get_demo_dir() 	
  screenshot_counter = screenshot_counter + 1	
  cv_img_filename = "%s/webcam_frame_%.2d.jpg" % (demo_dir, screenshot_counter)
  cv2.imwrite(filename=cv_img_filename, img=frame)

You can easily save an OpenCV image on disk using cv2.imwrite().

The post Python 3 and OpenCV Part 3: How to Read the Webcam with OpenCV (cv2) first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20200308/python-3-and-opencv-part-3-how-to-read-the-webcam-with-opencv-cv2/feed/ 1
Python 3 and OpenCV Part 2: How to Load an Image with OpenCV (and render it with GeeXLab) https://www.geeks3d.com/hacklab/20200306/python-3-and-opencv-part-2-how-to-load-an-image-with-opencv-and-render-it-with-geexlab/ https://www.geeks3d.com/hacklab/20200306/python-3-and-opencv-part-2-how-to-load-an-image-with-opencv-and-render-it-with-geexlab/#respond Fri, 06 Mar 2020 17:01:28 +0000 https://www.geeks3d.com/hacklab/?p=1498 Downloads: Python 3 Demopack Download Demo: geexlab-python3-demopack/opencv/02-image/main.xml GeeXLab Downloads Forum thread (EN)   This second tutorial will show you how to load an image with OpenCV and how to convert it to a GeeXLab texture for rendering. An OpenCV image is a NumPy array (numpy.ndarray). NumPy is one of the most important libraries for scientific computing in Python. It provides all you need to work … Continue reading Python 3 and OpenCV Part 2: How to Load an Image with OpenCV (and render it with GeeXLab) »

The post Python 3 and OpenCV Part 2: How to Load an Image with OpenCV (and render it with GeeXLab) first appeared on HackLAB.]]>

GeeXLab - Python 3 - How to load and image with OpenCV


Downloads:


 
This second tutorial will show you how to load an image with OpenCV and how to convert it to a GeeXLab texture for rendering.

An OpenCV image is a NumPy array (numpy.ndarray). NumPy is one of the most important libraries for scientific computing in Python. It provides all you need to work with multidimensional arrays. This article is not a tutorial about NumPy. I added some links about Numpy at the end of the article.

To load an image with OpenCV, we use the imread() function:

import cv2

demo_dir = gh_utils.get_demo_dir() 		
cv_image = cv2.imread(demo_dir + 'data/kool-image.jpg', cv2.IMREAD_COLOR)

The size of the image can be retrieved with:

im_height, img_width = cv_image.shape[0:2]

Now let’s see how to create a regular GeeXLab texture from this OpenCV image.

PF_U8_RGB = 1
PF_U8_BGR = 2
PF_U8_RGBA = 3

# BGR U8 is the default pixel format of OpenCV images.
# We create an empty texture
tex_image = gh_texture.create_2d(img_width, img_height, PF_U8_BGR)

# and we update the texture pixmap with the OpenCV image.
gh_texture.update_gpu_memory_from_numpy_img(tex_image, cv_image)

It’s done! We have now an GeeXLab texture filled with the data of an OpenCV image. It’s a detail but it can save you some time to know that OpenCV stores image pixels in BGR format…

The demo displays two images: the normal image and a smaller version of the same image. The smaller version has been created with the OpenCV resize() function:

img2_width = int(round(img_width/3))
img2_height = int(round(img_height/3))
cv_image2 = cv2.resize(cv_image,(img2_width, img2_height),interpolation=cv2.INTER_LINEAR) 

Another useful function is copyMakeBorder(). This function adds a border to an image. Here is the way to add a red border of 10 pixels:

cv_image2 = cv2.copyMakeBorder(cv_image2,
  top=10,
  bottom=10,
  left=10,
  right=10,
  borderType=cv2.BORDER_CONSTANT,
  value=(0, 0, 255))

For the color value, keep in mind that the pixel format is BGR…

Here is the demo:


GeeXLab - Python 3 - How to load and image with OpenCV

 
Links:

The post Python 3 and OpenCV Part 2: How to Load an Image with OpenCV (and render it with GeeXLab) first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20200306/python-3-and-opencv-part-2-how-to-load-an-image-with-opencv-and-render-it-with-geexlab/feed/ 0
(Python) How to Avoid .pyc Files https://www.geeks3d.com/hacklab/20190424/python-how-to-avoid-pyc-files/ https://www.geeks3d.com/hacklab/20190424/python-how-to-avoid-pyc-files/#comments Wed, 24 Apr 2019 15:13:36 +0000 https://www.geeks3d.com/hacklab/?p=1415 If you program in Python, you have certainly noticed that Python creates a folder named __pycache__ at several places. This folder is used by Python to store .pyc files which are Python bytecode files. They are created by the Python interpreter and can be used directly by Python’s virtual machine. Python source code is compiled into bytecode, the internal representation of a Python program in … Continue reading (Python) How to Avoid .pyc Files »

The post (Python) How to Avoid .pyc Files first appeared on HackLAB.]]>

Python logo

If you program in Python, you have certainly noticed that Python creates a folder named __pycache__ at several places. This folder is used by Python to store .pyc files which are Python bytecode files. They are created by the Python interpreter and can be used directly by Python’s virtual machine.

Python source code is compiled into bytecode, the internal representation of a Python program in the CPython interpreter. The bytecode is also cached in .pyc and .pyo files so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a virtual machine that executes the machine code corresponding to each bytecode. Do note that bytecodes are not expected to work between different Python virtual machines, nor to be stable between Python releases.
source.

If, for any reason, the generation of the bytecode cache bother you, here are some ways to avoid .pyc files:

 

1 – In C/C++

In C/C++, just use the following Python global variable somwhere before calling Py_Initialize():

Py_DontWriteBytecodeFlag = 1;
...
Py_Initialize();

 

2 – In Python

You can prevent the creation of the bytecode cache by using the following code in your initialization section of your Python script:

import sys
sys.dont_write_bytecode = True

 
Both techniques work in Python 2 and Python 3.

By default, GeeXLab allows the generation of .pyc files. So the solution to avoid them is to use sys.dont_write_bytecode=1 in the first lines of the first INIT script.

The post (Python) How to Avoid .pyc Files first appeared on HackLAB.]]>
https://www.geeks3d.com/hacklab/20190424/python-how-to-avoid-pyc-files/feed/ 1