def data2file(ret): file_name = (datetime.datetime.now()+datetime.timedelta(hours=8)).strftime("%Y%m%d%H") + '.txt' file_path = os.path.join(file_dir, file_name) with open(file_path, 'a') as file_object: file_object.write('\n'.join(ret)) file_object.write('\n')
时间: 2024-04-03 22:36:01 浏览: 21
这段代码已经很简洁了,但还有一些小优化可以考虑:
1. 可以使用pathlib模块来代替os.path.join,使代码更加简洁易读。
2. 可以使用with语句来自动关闭文件,避免手动关闭文件时出现的异常。
3. 可以将文件名的生成和文件写入操作分离开来,这样可以更灵活地使用文件名。
优化后的代码如下所示:
import pathlib
def data2file(ret, file_name=None):
if not file_name:
file_name = (datetime.datetime.now()+datetime.timedelta(hours=8)).strftime("%Y%m%d%H") + '.txt'
file_path = pathlib.Path(file_dir) / file_name
with open(file_path, 'a') as file_object:
file_object.write('\n'.join(ret))
file_object.write('\n')
相关问题
import cv2 import face_recognition import numpy as np from PIL import Image, ImageDraw,ImageFont video_capture = cv2.VideoCapture(r'C:/Users/ALIENWARE/123.mp4')#如果输入是(0)为摄像头输入 #现输入为MP4进行识别检测人脸 first_image = face_recognition.load_image_file("1.jpg") first_face_encoding = face_recognition.face_encodings(first_image)[0] Second_image = face_recognition.load_image_file("2.jpg") Second_face_encoding = face_recognition.face_encodings(Second_image)[0] third_image = face_recognition.load_image_file("3.jpg") third_face_encoding = face_recognition.face_encodings(third_image)[0] inside_face_encodings = [first_face_encoding,Second_face_encoding,third_face_encoding] inside_face_names = ['A','B','C'] face_locations = [] face_encodings = [] face_names = [] process_this_frame = True while True: ret, frame = video_capture.read() small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:, :, ::-1] if process_this_frame: face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: matches = face_recognition.compare_faces(inside_face_encodings, face_encoding) name = '未录入人脸' if True in matches: first_match_index = matches.index(True) name = inside_face_names[first_match_index] face_names.append(name) process_this_frame = not process_this_frame for (top, right, bottom, left), name in zip(face_locations, face_names): top *= 4 right *= 4 bottom *= 4 left *= 4 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) img_pil = Image.fromarray(frame) draw = ImageDraw.Draw(img_pil) fontStyle = ImageFont.truetype("C:/Windows/Fonts/simsun.ttc", 32, encoding="utf-8") draw.text((left + 6, bottom - 6), name, (0, 200, 0), font=fontStyle) frame = np.asarray(np.array(img_pil)) cv2.imshow('face_out', frame) if cv2.waitKey(1) & 0xFF == ord('q'): #退出需要按下Q键否则内核会崩溃 break video_capture.release() cv2.destroyAllWindows()
以下是修改后的代码,主要是添加了注释和一些规范化的修改:
```python
import cv2
import face_recognition
import numpy as np
from PIL import Image, ImageDraw, ImageFont
# 加载要识别的人脸图片
first_image = face_recognition.load_image_file("1.jpg")
first_face_encoding = face_recognition.face_encodings(first_image)[0]
Second_image = face_recognition.load_image_file("2.jpg")
Second_face_encoding = face_recognition.face_encodings(Second_image)[0]
third_image = face_recognition.load_image_file("3.jpg")
third_face_encoding = face_recognition.face_encodings(third_image)[0]
# 存储要检测的人脸编码及对应的人名
inside_face_encodings = [first_face_encoding, Second_face_encoding, third_face_encoding]
inside_face_names = ['A', 'B', 'C']
# 打开视频流
video_capture = cv2.VideoCapture(r'C:/Users/ALIENWARE/123.mp4')
# 循环读取视频帧
while True:
# 读取一帧
ret, frame = video_capture.read()
# 降低帧率,加快处理速度
if not ret:
break
# 缩小图片尺寸,加快处理速度
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = small_frame[:, :, ::-1]
# 处理每一帧图片
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
# 遍历每个检测到的人脸
for face_encoding in face_encodings:
# 比对人脸编码
matches = face_recognition.compare_faces(inside_face_encodings, face_encoding)
name = '未录入人脸'
# 找到匹配的人脸
if True in matches:
first_match_index = matches.index(True)
name = inside_face_names[first_match_index]
face_names.append(name)
# 在画面上标记人脸及名字
for (top, right, bottom, left), name in zip(face_locations, face_names):
# 将坐标放大4倍,因为之前缩小了4倍
top *= 4
right *= 4
bottom *= 4
left *= 4
# 画出人脸框
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
# 添加名字
img_pil = Image.fromarray(frame)
draw = ImageDraw.Draw(img_pil)
fontStyle = ImageFont.truetype("C:/Windows/Fonts/simsun.ttc", 32, encoding="utf-8")
draw.text((left + 6, bottom - 6), name, (0, 200, 0), font=fontStyle)
frame = np.asarray(np.array(img_pil))
# 显示画面
cv2.imshow('face_out', frame)
# 按下q键退出程序
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放视频流
video_capture.release()
# 关闭所有窗口
cv2.destroyAllWindows()
```
import cv2 import os from tqdm import tqdm def extract_frames(input_directory, output_directory, temp_directory): for video_file in os.listdir(input_directory): if not video_file.endswith('.mp4'): continue video_path = os.path.join(input_directory, video_file) video_name = os.path.splitext(video_file)[0] output_folder = os.path.join(output_directory, video_name) os.makedirs(output_folder, exist_ok=True) capture = cv2.VideoCapture(video_path) frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) # 逐帧提取图像,并保存为JPEG格式的文件 for i in tqdm(range(frame_count)): capture.set(cv2.CAP_PROP_POS_FRAMES, i) ret, frame = capture.read() if ret: frame_path = os.path.join(output_folder, f'{i}.jpg') cv2.imwrite(frame_path, frame) print(f'已保存图片:{frame_path}') # 添加debug信息 if __name__ == '__main__': input_directory = r'C:\\Users\\Administrator\\Desktop\\空调被\\视频' output_directory = r'C:\\Users\\Administrator\\Desktop\\空调被\\图片' temp_directory = r'C:\\Users\\Administrator\\Desktop\\空调被\\临时' extract_frames(input_directory, output_directory, temp_directory)debug的信息提示路径是对的,但是在文件夹内没有保存的图片
这段代码是用来从视频文件中逐帧提取图像,并保存为JPEG格式的文件。如果你在程序运行时看到了"已保存图片"的输出,但是在文件夹内没有找到保存的图片,有可能是以下原因导致:
1. 文件夹权限问题:请检查你保存图片的文件夹是否有读写权限。
2. 文件夹不存在:如果你指定的文件夹不存在,程序会自动创建一个新的文件夹,但是如果你的输入路径或输出路径有错别字或者拼写错误,也可能会导致程序无法正确识别文件夹。
3. 保存路径问题:请检查你保存图片的完整路径是否正确,包括路径分隔符和文件名后缀等。如果路径有误,程序将无法正确保存图片。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)