图片中行人检测GUI代码
时间: 2024-05-05 22:21:03 浏览: 59
以下是行人检测GUI代码的示例:
```python
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
# Load pedestrian detection cascade classifier
pedestrian_cascade = cv2.CascadeClassifier('haarcascade_fullbody.xml')
class PedestrianDetectionGUI:
def __init__(self, master):
self.master = master
master.title("Pedestrian Detection")
# Create buttons
self.select_image_button = tk.Button(master, text="Select Image", command=self.select_image)
self.detect_pedestrian_button = tk.Button(master, text="Detect Pedestrian", command=self.detect_pedestrian)
# Create canvas for displaying image
self.canvas = tk.Canvas(master, width=400, height=400)
# Pack buttons and canvas
self.select_image_button.pack()
self.detect_pedestrian_button.pack()
self.canvas.pack()
# Initialize variables
self.image = None
self.image_path = None
def select_image(self):
# Open file dialog to select image
self.image_path = filedialog.askopenfilename()
# Load image and display on canvas
self.image = Image.open(self.image_path)
self.image = self.image.resize((400, 400), Image.ANTIALIAS)
self.image_tk = ImageTk.PhotoImage(self.image)
self.canvas.create_image(0, 0, anchor='nw', image=self.image_tk)
def detect_pedestrian(self):
if self.image is not None:
# Load image in grayscale
img = cv2.imread(self.image_path, cv2.IMREAD_GRAYSCALE)
# Detect pedestrians using cascade classifier
pedestrians = pedestrian_cascade.detectMultiScale(img, 1.3, 5)
# Draw rectangles around detected pedestrians
for (x, y, w, h) in pedestrians:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
# Convert image back to RGB and display on canvas
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
img = Image.fromarray(img)
img = img.resize((400, 400), Image.ANTIALIAS)
img_tk = ImageTk.PhotoImage(img)
self.canvas.create_image(0, 0, anchor='nw', image=img_tk)
else:
# Display error message if no image is selected
tk.messagebox.showerror("Error", "No image selected.")
# Create GUI window
root = tk.Tk()
gui = PedestrianDetectionGUI(root)
root.mainloop()
```
这个示例代码使用 `tkinter` 模块创建了一个简单的 GUI 窗口,其中包括两个按钮和一个画布。当用户点击“Select Image”按钮时,程序会打开文件对话框,让用户选择一张图片。当用户点击“Detect Pedestrian”按钮时,程序会使用 Haar 级联分类器检测行人,并在画布上显示检测结果。
阅读全文