如何将文件保存到某个目录

2024-05-19 00:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将图片保存到目录中的文件夹中。我在tkinter中有一个按钮,它有一个命令,可以拍摄相机输出的照片。我需要能够将这张照片保存在一个特定的文件中,这样我的面部识别就可以在上面进行训练。我不知道如何将图像保存到文件夹中。非常感谢您的帮助

代码:

    from tkinter import *
from tkinter import filedialog
import cv2 as cv
import sys
from PIL import Image, ImageTk
import numpy as np
from PIL import Image, ImageTk
import os
import datetime
from socket import *

# stuff
root = Tk()
root.title('Real-Time Facial Detection/Recognition')
root.geometry('1400x700')
root.configure(bg='gray15')
root.resizable(0, 0)
global img
global test123

# button functions

def detect_on():
    global img
    global test123
    test123 = 2
    while test123 == 2:
        haar_cascade = cv.CascadeClassifier('haar_face.xml')
        img = cam.read()[1]
        faces_rect = haar_cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=10)

        for (x,y,w,h) in faces_rect:
            img = cv.rectangle(img, (x,y), (x+w,y+h), (0,255,0), thickness=2)

        img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
        img = ImageTk.PhotoImage(Image.fromarray(img))
        L1['image'] = img
        root.update()

def detect_off():
    global img
    global test123
    test123 = 1
    img = cam.read()[1]
    img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    img = ImageTk.PhotoImage(Image.fromarray(img))
    L1['image'] = img
    root.update()

def recog_on():
    global img
    global test123
    global name_gotten
    name_gotten = name_box.get()
    test123 = 3
    while test123 == 3:
        haar_cascade = cv.CascadeClassifier('haar_face.xml')

        people = ['Henry']

        face_recognizer = cv.face.LBPHFaceRecognizer_create()
        face_recognizer.read('face-trained2.yml')

        img = cam.read()[1]
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

        # detect the face
        if True:
            faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10)

            for (x,y,w,h) in faces_rect:
                faces_roi = gray[y:y+h, x:x+w]

                label, confidence = face_recognizer.predict(faces_roi)
                print(f'Label = {people[label]} with a confidence of {confidence}')

                cv.putText(img, str(people[label]), (x+2,y+h-5), cv.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), thickness=2)
                cv.rectangle(img, (x-5,y-5), (x+w,y+h),(0,255,0), thickness=2)

            img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
            img = ImageTk.PhotoImage(Image.fromarray(img))
            L1['image'] = img
            root.update()

def recog_off():
    global img
    global test123
    test123 = 1
    img = cam.read()[1]
    img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    img = ImageTk.PhotoImage(Image.fromarray(img))
    L1['image'] = img
    root.update()

def take_picture():
    name_gotten = name_box.get()
    directory = f'{name_gotten}'
    parent_dir = 'C:/OCV/real-time-FR'
    path = os.path.join(parent_dir, directory)
    os.mkdir(path)




    image1 = Image.fromarray(img1)
    time = str(datetime.datetime.now().today())
    time2 = time.replace(':',' ') + '.jpg'
    image1.save(f'{path}', time2)

def name_get():
    global name_gotten
    name_gotten = name_box.get()
    print(name_gotten)
    print(type(name_gotten))

# buttons
Face_detect_on = Button(root, text='Start FD', padx=75, pady=25, bg='black', fg='white', font=('Calibri', 30, 'bold'), borderwidth=0, command=detect_on)
Face_detect_on.place(x=35, y=180)

Face_detect_off = Button(root, text='Stop FD', padx=75, pady=25, bg='black', fg='white', font=('Calibri', 30, 'bold'), borderwidth=0, command=detect_off)
Face_detect_off.place(x=35, y=380)

# FR buttons
Face_recog_on = Button(root, text='Start FR', padx=75, pady=25, bg='black', fg='white', font=('Calibri', 30, 'bold'), borderwidth=0, command=recog_on)
Face_recog_on.place(x=1060, y=180)

Face_recog_off = Button(root, text='Stop FR', padx=75, pady=25, bg='black', fg='white', font=('Calibri', 30, 'bold'), borderwidth=0, command=recog_off)
Face_recog_off.place(x=1060, y=380)

picture = Button(root, text='Picture', padx=50, pady=25, bg='black', fg='white', font=('Calibri', 15, 'bold'), borderwidth=0, command=take_picture)
picture.place(x=1060, y=430)

name_text = Label(root, text='Name:', bg='black', fg='white', font=('Calibri', 11, 'bold'))
name_text.place(x=1055, y=332)

name_enter = Button(root, text='Enter', bg='black', fg='white', font=('Calibri', 11, 'bold'), borderwidth=0, command=name_get)
name_enter.place(x=1276, y=330)

name_box = Entry(root, bg='black', width=17, fg='white', font=('Calibri', 15, 'bold'), borderwidth=0)
name_box.place(x=1103, y=331)

Label(root, text='Camera Output', font=('Calibri', 50, 'bold'), bg='gray15', fg='white').pack()
f1 = LabelFrame(root, bg='white')
f1.pack()
L1 = Label(f1, bg='white')
L1.pack()
test123 = 1
cam = cv.VideoCapture(0)

while test123 == 1:
    global img
    img = cam.read()[1]
    img1 = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    img = ImageTk.PhotoImage(Image.fromarray(img1))
    L1['image'] = img
    root.update()

root.mainloop()

我正在和最后几行打交道。Plz帮助 错误:

    Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python37\lib\tkinter\__init__.py", line 1884, in __call__
    return self.func(*args)
  File "C:\OCV\real-time FR\testforrealtimefd.py", line 108, in take_picture
    image1.save(time2, f'{path}')
  File "C:\Python37\lib\site-packages\PIL\Image.py", line 2153, in save
    save_handler = SAVE[format.upper()]
KeyError: 'C:/OCV/REAL-TIME FR\\TEST #1'

Tags: textnameimageimportimgrootglobalcv

热门问题