face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def detect_faces(img, draw_box=True): # convert image to grayscale grayscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # detect faces faces = face_cascade.detectMultiScale(grayscale_img, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) face_box, face_coords = None, [] for (x, y, w, h) in faces: if draw_box: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 5) face_box = img[y:y+h, x:x+w] face_coords = [x,y,w,h] return img, face_box, face_coords if __name__ == "__main__": files = os.listdir('sample_faces') images = [file for file in files if 'jpg' in file] for image in images: img = cv2.imread('sample_faces/' + image) detected_faces, _, _ = detect_faces(img) cv2.imwrite('sample_faces/detected_faces/' + image, detected_faces)做一个可视化界面,要求可以拖进去图片,并且显示处理后的图片
时间: 2023-12-01 14:03:36 浏览: 215
好的,你可以使用Python的Tkinter库来创建一个GUI界面。以下是一个简单的示例代码:
```python
import cv2
import os
import tkinter as tk
from tkinter import filedialog
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def detect_faces(img, draw_box=True):
# convert image to grayscale
grayscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# detect faces
faces = face_cascade.detectMultiScale(grayscale_img, scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
face_box, face_coords = None, []
for (x, y, w, h) in faces:
if draw_box:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 5)
face_box = img[y:y+h, x:x+w]
face_coords = [x,y,w,h]
return img, face_box, face_coords
def open_file():
file_path = filedialog.askopenfilename()
if file_path:
img = cv2.imread(file_path)
detected_faces, _, _ = detect_faces(img)
cv2.imshow('Detected Faces', detected_faces)
cv2.waitKey(0)
cv2.destroyAllWindows()
root = tk.Tk()
root.title('Face Detection')
root.geometry('300x100')
button = tk.Button(root, text='Open Image', command=open_file)
button.pack(pady=20)
root.mainloop()
```
这个程序会创建一个窗口,并在窗口中添加一个“Open Image”按钮。当你点击按钮时,会弹出一个文件选择对话框,你可以选择要处理的图片。选择好图片后,程序会自动进行人脸检测,并在新窗口中显示处理后的图片。
阅读全文