杰瑞科技汇

creattrackbar python

Of course! Creating a custom trackbar in Python is a common task, especially in computer vision applications. The most popular library for this is OpenCV.

creattrackbar python-图1
(图片来源网络,侵删)

I'll guide you through it, starting with the simplest case and then moving to more advanced, flexible solutions.

Method 1: The Classic OpenCV Way (Simple & Direct)

This is the most straightforward method, perfect for creating a trackbar that controls a parameter in real-time (like a threshold value). The trackbar is attached directly to an OpenCV window.

Key Concepts:

  1. cv2.createTrackbar(): This function creates a trackbar and attaches it to a specified window.
  2. cv2.getTrackbarPos(): This function retrieves the current integer value of the trackbar.
  3. cv2.setTrackbarPos(): This function programmatically sets the trackbar's position.

Example: Live Thresholding with a Trackbar

This example creates a window with a trackbar. As you move the slider, the threshold for a binary image updates in real-time.

import cv2
import numpy as np
# --- 1. Setup ---
# Create a black image and a window to display it
img = np.zeros((300, 512, 3), np.uint8)
window_name = 'Image'
cv2.namedWindow(window_name)
# --- 2. Define the Callback Function ---
# This function is called every time the trackbar is moved.
# Its arguments are the trackbar position and the user data (we'll pass the image).
def nothing(x):
    """Callback function for the trackbar. Does nothing, but is required."""
    pass
# --- 3. Create the Trackbar ---
# cv2.createTrackbar(trackbarName, windowName, initialValue, maxValue, callbackFunction)
trackbar_name = 'Threshold'
initial_value = 0
max_value = 255
cv2.createTrackbar(trackbar_name, window_name, initial_value, max_value, nothing)
# --- 4. Main Loop ---
while True:
    # Get the current position of the trackbar
    threshold_value = cv2.getTrackbarPos(trackbar_name, window_name)
    # Create a dummy grayscale image for thresholding
    # In a real app, you'd load an image here, e.g., img_gray = cv2.imread('image.jpg', 0)
    dummy_gray_img = np.ones((300, 512), dtype=np.uint8) * 128 # A mid-gray image
    # Apply the threshold
    _, thresh_img = cv2.threshold(dummy_gray_img, threshold_value, 255, cv2.THRESH_BINARY)
    # Display the thresholded image in the window
    cv2.imshow(window_name, thresh_img)
    # Wait for a key press. If 'q' is pressed, break the loop.
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'):
        break
# --- 5. Cleanup ---
cv2.destroyAllWindows()

How to Run:

creattrackbar python-图2
(图片来源网络,侵删)
  1. Save the code as a Python file (e.g., trackbar_example.py).
  2. Make sure you have OpenCV installed (pip install opencv-python).
  3. Run from your terminal: python trackbar_example.py.
  4. A window will appear. Move the slider to see the threshold effect. Press 'q' to quit.

Method 2: Using Tkinter (More GUI Flexibility)

If you are building a larger GUI application using Tkinter, you might want to embed the trackbar within a Tkinter window. Tkinter has its own slider widget called Scale.

This example shows how to create a Tkinter window with a slider that updates an OpenCV image.

Key Concepts:

  1. tk.Scale: The Tkinter widget for a slider/trackbar.
  2. cv2.cvtColor(): To convert between OpenCV's BGR format and Tkinter's PhotoImage-compatible RGB format.
  3. PIL.Image and ImageTk.PhotoImage: To convert a NumPy array (OpenCV image) into a format Tkinter can display.

Example: Tkinter Trackbar Controlling an OpenCV Image

import cv2
import numpy as np
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
class App:
    def __init__(self, root):
        self.root = root
        self.root.title("Tkinter Trackbar with OpenCV")
        # --- 1. Create a dummy image ---
        self.img = np.zeros((300, 512, 3), np.uint8)
        self.img[:] = (128, 128, 128) # Fill with gray
        # --- 2. Create Tkinter Widgets ---
        # Frame to hold the image
        self.image_frame = ttk.Frame(self.root, padding="10")
        self.image_frame.pack()
        # Label to display the image
        self.label = ttk.Label(self.image_frame)
        self.label.pack()
        # Frame to hold the slider
        self.slider_frame = ttk.Frame(self.root, padding="10")
        self.slider_frame.pack()
        # The Tkinter Scale (trackbar) widget
        # from_=min, to=max, orient=horizontal, command=self.update_image
        self.slider = ttk.Scale(
            self.slider_frame,
            from_=0,
            to=255,
            orient=tk.HORIZONTAL,
            length=300,
            command=self.update_image
        )
        self.slider.set(128) # Initial value
        self.slider.pack()
        # Initial image display
        self.update_image()
    def update_image(self, value=None):
        """Callback for the slider. Updates the image based on slider value."""
        # Get the value from the slider
        slider_value = int(self.slider.get())
        # Modify the image based on the slider value
        # For example, change the blue channel
        self.img[:, :, 0] = slider_value
        # Convert the image from BGR (OpenCV) to RGB (Tkinter/Pillow)
        img_rgb = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
        # Convert to a PIL Image
        img_pil = Image.fromarray(img_rgb)
        # Convert to a Tkinter PhotoImage
        photo = ImageTk.PhotoImage(image=img_pil)
        # Update the label's image
        self.label.configure(image=photo)
        # Keep a reference to prevent garbage collection
        self.label.image = photo
if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

How to Run:

  1. Save the code.
  2. Make sure you have the required libraries: pip install opencv-python pillow.
  3. Run: python tkinter_trackbar_example.py.
  4. A Tkinter window will appear. Drag the slider to see the blue channel of the image change.

Method 3: Using PySide6 / PyQt6 (Modern & Powerful GUI)

For professional, modern desktop applications, PySide6 (or its twin PyQt6) is an excellent choice. It has a more powerful slider called QSlider.

creattrackbar python-图3
(图片来源网络,侵删)

This approach is similar to the Tkinter method but uses Qt's widgets and signal/slot mechanism.

Example: PySide6 Trackbar

import sys
import cv2
import numpy as np
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QSlider, QVBoxLayout, QWidget
from PySide6.QtCore import Qt
from PySide6.QtGui import QImage, QPixmap
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PySide6 Trackbar")
        self.setGeometry(100, 100, 600, 400)
        # --- 1. Create a dummy image ---
        self.img = np.zeros((300, 512, 3), dtype=np.uint8)
        self.img[:] = (128, 128, 128)
        # --- 2. Create Widgets ---
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(0)
        self.slider.setMaximum(255)
        self.slider.setValue(128)
        self.slider.valueChanged.connect(self.update_image)
        # --- 3. Layout ---
        layout = QVBoxLayout()
        layout.addWidget(self.image_label)
        layout.addWidget(self.slider)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
        # --- 4. Initial display ---
        self.update_image()
    def update_image(self):
        """Slot connected to the slider's valueChanged signal."""
        value = self.slider.value()
        # Modify image (e.g., green channel)
        self.img[:, :, 1] = value
        # Convert NumPy array to QImage
        # QImage needs to be in RGB format
        height, width, channel = self.img.shape
        bytes_per_line = 3 * width
        q_img = QImage(self.img.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
        # Convert QImage to QPixmap and set it to the label
        pixmap = QPixmap.fromImage(q_img)
        self.image_label.setPixmap(pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show
分享:
扫描分享到社交APP
上一篇
下一篇