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