Create a picture viewer application using PyQt5

Create an image viewer application using PyQt5

Author: Quiet to Silent Personal Homepage

In this tutorial, we will create a simple image viewer application using the PyQt5 library. This application displays a series of images and allows users to switch and jump to different images with buttons.

1. Preparation

First, we need to install the PyQt5 library. Open a terminal or command prompt and run the following command:

pip install PyQt5

Make sure you have Python and pip installed and running.

2. Create the main program

Create a Python file named image_viewer.py and copy the following code into it:

import sys
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QPushButton, QLineEdit
from PyQt5.QtGui import QPixmap

# Image path
images = [
    'F:/BaiduSyncdisk/Picture/n02009912_2248_Highgreen.JPEG',
    'F:/BaiduSyncdisk/Picture/n02013706_161_Highgreen.JPEG',
    'F:/BaiduSyncdisk/Picture/n02281787_2344_Highblue.JPEG',
    'F:/BaiduSyncdisk/Picture/n02281787_2354_Highblue.JPEG'

]
current_index = 0 # Currently displayed image index

def show_image():
    pixmap = QPixmap(images[current_index])
    label.setPixmap(pixmap)
    label.resize(pixmap.width(), pixmap.height())
    filename_label.setText(f'File name: {<!-- -->images[current_index]}')

def next_image():
    global current_index
    current_index = (current_index + 1) % len(images) # Loop to the next image
    show_image()

def previous_image():
    global current_index
    current_index = (current_index - 1) % len(images) # Loop to the previous image
    show_image()

def jump_to_image():
    global current_index
    index_str = input_box.text().strip() # Get the index string in the input box
    if index_str.isdigit(): # If the input is a number
        index = int(index_str) - 1 # Convert the index to a number and subtract 1 (because the list starts at 0)
        if 0 <= index < len(images): # If the index is within the range of the image list
            current_index = index # Jump to the corresponding picture
            show_image()

app = QApplication(sys.argv)
window = QMainWindow()
window.setGeometry(200, 350, 500, 400)

label = QLabel(window)
label.setGeometry(130, 20, 100, 100) #Adjust position and size
window.setWindowTitle('Picture Viewer')

filename_label = QLabel(window)
filename_label.setGeometry(100, 280, 380, 30)
show_image()

previous_button = QPushButton('Previous picture', window)
previous_button.move(70, 320)
previous_button.clicked.connect(previous_image)

next_button = QPushButton('next picture', window)
next_button.move(320, 320)
next_button.clicked.connect(next_image)

input_box = QLineEdit(window)
input_box.move(200, 320)

jump_button = QPushButton('jump', window)
jump_button.move(200, 360)
jump_button.clicked.connect(jump_to_image)

window.show()
sys.exit(app.exec_())

This code defines an application that contains image viewer functionality. Specifically, it uses various widgets (widgets) provided by the PyQt5 library, such as QLabel, QMainWindow, QPushButton, QLineEdit, etc.

3. Run the application

Save and run the image_viewer.py file and you will see a simple image viewer application interface. It displays the first image and provides buttons for previous, next, and jump to the specified image.

You can click the corresponding button to switch pictures or jump to a specified picture. The image’s file name is also displayed at the bottom of the window.

Conclusion insert picture description here

In this tutorial, we created a simple image viewer application using the PyQt5 library. This app helps you browse and switch between different pictures.

You can further expand this application according to actual needs, such as adding more function buttons, supporting more image formats, etc.

Hope this tutorial helps you! If you have any questions or queries, please feel free to leave them in the comments section.

Recommended column

Pattern recognition and artificial intelligence (programs and algorithms)

Machine learning MATLAB implementation
  1. Machine learning MATLAB implementation: Matalb-neighborhood average method, mean filter method, median filter method to smooth and denoise images_neighborhood average filtering
  2. Machine learning MATLAB implementation: MATLAB-histogram equalization_matlab histogram equalization
  3. Machine learning MATLAB implementation: JPEG image compression based on DCT transform_dct transform image compression
  4. Machine learning MATLAB implementation: Matalb-image mean filtering, median filtering, gradient sharpening (sobel operator) implementation_matlab sobel filtering
  5. Machine learning MATLAB implementation: Matlab-gradient Roberts operator, Laplacian operator, Sobel operator, and Prewitt operator to sharpen images
Deep Learning
  1. Deep learning parameter adjustment experience: eight key steps to optimize neural network performance
Python example
  1. Python code example: Copy untagged files in one folder to another

  2. Python code example: Compare file names in two folders and print identical files

  3. Python code example: Use the Pillow library to easily implement image resizing -> Make each image the same size to facilitate model processing and training_pillow Get image size_Quiet to Silent Blog-CSDN Blog

  4. Python code example: Find the mean and variance of the pictures in the folder -> eliminate abnormal data, ensure that all pixel values are within a reasonable range, and improve the performance of the model. _Quiet to Silent Blog-CSDN Blog

  5. Python code example: Use Python’s Pillow library to format and rename images

  6. Python code example: Use Python code to modify file names in batches_Batch modify file names

  7. Python code example: iterate through image information in a text file and copy the image

  8. Python code example: Python implements merging and splitting Imagenet data sets

  9. Python code example: AI assistant helps you easily rename and copy Imagenet data sets

  10. Python code example: python implementation to obtain the tree structure in the current directory_python reads the directory structure

  11. Python code example: Use ChatGPT to quickly convert grayscale and RGBA images to RGB three-channel images for Python data cleaning demo_python rgba to rgb

  12. Python code example: How to convert the image read through Image.open from single channel to three channel

  13. Use Python to batch change the names of pictures in a folder_python to modify picture names

  14. Python code example: Crawl website images

  15. Python code example: List Comprehensions and its conditional filtering method in Python_python list comprehension multiple conditions

Opencv-python tutorial
  1. Opencv-python tutorial: basic operations of python-opencv(1) images
  2. Opencv-python tutorial: python-opencv(2) image operation
  3. Opencv-python tutorial: python-opencv(3) image type conversion
  4. Opencv-python tutorial: python-opencv(4)–geometric transformation
  5. Opencv-python tutorial: python-opencv(10) image pyramid
  6. Opencv-python tutorial: python-opencv(11) image contour
  7. Opencv-python tutorial: python-opencv(12) histogram
  8. Opencv-python tutorial: python-opencv(13) Fourier transform
Pattern recognition and machine learning (implemented in Python)
  1. Pattern recognition and machine learning (Python implementation): Male and female classification based on sklearn naive Bayes model and pazen window method
  2. Pattern recognition and machine learning (Python implementation): a simple implementation of skin detection based on Bayesian decision-making
  3. Pattern recognition and machine learning (Python implementation): Face recognition based on PCA dimensionality reduction and KNN classification
  4. Pattern recognition and machine learning (Python implementation): Face recognition based on PCA–LDA
  5. Pattern recognition and machine learning (Python implementation): Image segmentation based on clustering
  6. Pattern recognition and machine learning (implemented in Python): Decision trees are divided into men and women
  7. Pattern recognition and machine learning (Python implementation): classification problem based on compressed nearest neighbor method
  8. Pattern recognition and machine learning (Python implementation): How to use MCMC to generate arbitrary probability distribution random numbers? Python simple implementation
Tensorflow learning

Tensorflow1.x

  1. Tensorflow1.x: tensor and numpy in tf
  2. Tensorflow1.x: The role of trainable in tf.Variable
  3. Tensorflow1.x: tesorflow calculates model complexity
  4. Tensorflow1.x: L2 regularization and collection [tf.GraphKeys]
  5. Tensorflow1.x: Tensorflow variables and shared variables

Tensorflow2.x

  1. Tensorflow2.x: Steps to create keras environment
  2. Tensorflow2.x: tensorflow2.0 deep learning basics and tf.keras
  3. Tensorflow2.x: Implementation example of tensorflow2.0 convolutional neural network (satellite and lake)
  4. Tensorflow2.x: tensorflow2.0 tf.keras sequence problem
  5. Tensorflow2.x: tensorflow2.0 instance cat and dog recognition (1)
  6. Tensorflow2.x: tensorflow2.0 eager mode and custom training network
  7. Tensorflow2.x: tensorflow2.0 tf.keras cat and dog recognition (2)-custom training
  8. Tensorflow2.x: tebsorflow2.0 uses Keras to write custom layers and models
  9. Tensorflow2.x: tebsorflow2.0 multi-output model example
  10. Tensorflow2.x: tebsorflow2.0 image positioning + classification (Oxford-IIIT data set)
  11. Tensorflow2.x: tebsorflow2.0 image semantic segmentation (Oxford-IIIT data set)
Python syntax
  1. Python syntax: specific usage of hasattr in Python
  2. Python syntax: syntax usage in python (easydict set() plt.subplots() assert)
  3. Python syntax: Use of common functions in the os.path library_The functions in the standard library os.path are used to obtain parameter specifications
  4. Python syntax: A brief summary of how to use argparse_argparse usage in python
  5. Python syntax: python __all__ meaning
  6. Python syntax: numpy method accumulation
  7. Python syntax: How to learn the getattr() function elegantly
  8. How to specify GPU in pycharm
Pytorch syntax
  1. Pytorch syntax: pack_padded_sequence usage and complete example
  2. Pytorch syntax: torch.manual_seed() in pytorch
  3. Pytorch syntax: torch.autograd.Function learning and understanding
  4. Pytorch syntax: Why set cudnn.benchmark=True
  5. Pytorch syntax: pytorch weight initialization_pytorch weight initialization
  6. Pytorch syntax: accumulation of pytorch usage methods
  7. Pytorch syntax: How to load partial weights with Pytorch
Dataset usage
  1. Explanation, installation and use of pycocotools data set_Quiet to Silent Blog-CSDN Blog
Linux Debugging
  1. Linux debugging: change the CUDA version _How to change the cuda version
  2. Linux debugging: linux operation command_vi train.py
  3. Linux debugging: How to elegantly solve Pycharm’s Port problem in jupyter notebook
  4. Linux debugging: How to elegantly decompress a specified folder under linux_decompress a single file in linux
  5. Linux debugging: moving and copying folders under Linux_linux copy the entire folder
  6. Linux Debugging: How to Use GPU Monitoring Elegantly
  7. Linux debugging: How to run tensorboard on a remote server and see the operation on the local server
Bug debugging
  1. Bug Debugging: Successfully resolved OSError: [E050] Can’t find model en_core_web_sm’._
  2. Bug Debugging: Successfully solved Resource punkt not found error
  3. Bug debugging: Successfully solved the installation error of NLTK package
  4. Bug debugging: Successfully resolved http.client.RemoteDisconnected: Remote end closed connection without response
  5. Successfully solved: ValueError Cannot assign non-leaf Tensor to parameter weight.md
  6. Successfully resolved AttributeError: module torch.distributed has no attribute all_gather_base
  7. Successfully solved ImportError: /home/mona/research/code/frankmocap/detectors/hand_object_detector/lib/model/C.cpy
  8. Successfully solved the problem of installing spacy==2.x: successfully solved sre_constants.error: bad escape \p at position 173-CSDN Blog
  9. Successfully solved the problem of installing spacy==2.x: OSError: E050] Cant find model en_core_web_sm. It doesnt seem to be …_
Others
  1. Commonly used underwater image data sets
  2. “Micro Weather” – an intelligent weather forecast experience based on WeChat applet_Weather forecast applet development