乐闻世界logo
搜索文章和话题

How to display random image from USB on a Pi

1个答案

1

To display random images from a USB device on Raspberry Pi, follow these steps to achieve this. Below are the detailed steps and relevant code examples:

Step 1: Prepare the Environment

First, ensure that the Raspberry Pi operating system (typically Raspberry Pi OS) is up to date and has the necessary software installed, such as Python and PIL (Python Imaging Library, now known as Pillow).

bash
sudo apt-get update sudo apt-get upgrade sudo apt-get install python3-pil python3-pil.imagetk

Step 2: Connect the USB Device

Insert the USB device containing image files into the Raspberry Pi's USB port. Use the lsblk or fdisk -l command to check the device name, which is typically sda1 or similar.

bash
sudo fdisk -l

Step 3: Mount the USB Device

After identifying the USB device, mount it to a directory on the Raspberry Pi, such as /mnt/usb.

bash
sudo mkdir /mnt/usb sudo mount /dev/sda1 /mnt/usb

Step 4: Write the Python Script

Write a Python script to randomly select an image file and display it using the Pillow library.

python
import os import random from PIL import Image, ImageTk from tkinter import Tk, Label def show_random_image(directory): # Get all files in the directory files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith(('png', 'jpg', 'jpeg'))] # Randomly select an image file img_path = random.choice(files) # Open the image using Pillow img = Image.open(img_path) # Create a GUI window to display the image using Tkinter root = Tk() tkimage = ImageTk.PhotoImage(img) Label(root, image=tkimage).pack() root.mainloop() # Call the function with the mount point of the USB device show_random_image('/mnt/usb')

Step 5: Run the Script

Save the above script as display_random_image.py and run it on the Raspberry Pi.

bash
python3 display_random_image.py

This way, each time you run the script, it will randomly select an image file from the mounted USB device and display it.

Common Issue Resolution

  1. Permission Issues: If you encounter permission issues when accessing the USB device, run the script as the root user or change the permissions of the mount point.
  2. Dependency Issues: Ensure all required libraries are correctly installed, such as PIL/Pillow and Tkinter.
  3. Image Format Issues: Verify that the image formats defined in the script match those of the images on the USB device.

This completes the full process for displaying random images from USB on Raspberry Pi.

2024年8月21日 00:51 回复

你的答案