ACCA225 commited on
Commit
0c834e5
1 Parent(s): 4b89fed

Upload 2 files

Browse files
Files changed (2) hide show
  1. Downloads.7z +3 -0
  2. 并行优化版本(1) (1).py +413 -0
Downloads.7z ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de411830ffafad5c374641e688687e9b4569f715376b949275e1739b40e2ce27
3
+ size 2228098
并行优化版本(1) (1).py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import shutil
3
+ import av
4
+ import os
5
+ import cv2
6
+ import sys
7
+ import time
8
+ import multiprocessing
9
+ import tkinter as tk
10
+ from tkinter import filedialog
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from PIL import Image
13
+ import numpy as np
14
+ from collections import defaultdict
15
+ from waifuc.action import MinSizeFilterAction, PersonSplitAction
16
+ from waifuc.export import SaveExporter, TextualInversionExporter
17
+ from waifuc.source import LocalSource
18
+ from tqdm import tqdm
19
+ import logging
20
+
21
+ # 配置日志
22
+ logging.basicConfig(filename='video_image_processing.log', level=logging.INFO,
23
+ format='%(asctime)s - %(levelname)s - %(message)s')
24
+
25
+
26
+ def select_folder():
27
+ """
28
+ 弹出文件夹选择对话框,返回选择的文件夹路径。
29
+ """
30
+ root = tk.Tk()
31
+ root.withdraw() # 隐藏主窗口
32
+ folder_path = filedialog.askdirectory(title="选择视频文件夹")
33
+ return folder_path
34
+
35
+
36
+ def create_output_folder(folder_path, extra_name):
37
+ """
38
+ 创建输出文件夹,文件夹名称为原名称加上额外的后缀。
39
+
40
+ 参数:
41
+ folder_path (str): 原文件夹路径。
42
+ extra_name (str): 要添加到文件夹名称后的字符串。
43
+
44
+ 返回:
45
+ str: 新创建的文件夹路径。
46
+ """
47
+ folder_name = os.path.basename(folder_path)
48
+ new_folder_name = f"{folder_name}{extra_name}"
49
+ new_folder_path = os.path.join(folder_path, new_folder_name)
50
+ os.makedirs(new_folder_path, exist_ok=True)
51
+ return new_folder_path
52
+
53
+
54
+ def find_video_files(folder_path):
55
+ """
56
+ 在指定文件夹及其子文件夹中查找所有视频文件。
57
+
58
+ 参数:
59
+ folder_path (str): 文件夹路径。
60
+
61
+ 返回:
62
+ list: 视频文件的完整路径列表。
63
+ """
64
+ video_extensions = ('.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv')
65
+ video_files = []
66
+ for root, dirs, files in os.walk(folder_path):
67
+ for file in files:
68
+ if file.lower().endswith(video_extensions):
69
+ video_files.append(os.path.join(root, file))
70
+ return video_files
71
+
72
+
73
+ def process_video(video_file, new_folder_path, frame_step=5):
74
+ """
75
+ 处理视频文件,提取帧,计算哈希和清晰度,保存符合条件的帧。
76
+
77
+ 参数:
78
+ video_file (str): 视频文件路径。
79
+ new_folder_path (str): 保存提取帧的文件夹路径。
80
+ frame_step (int): 帧步长,每隔多少帧处理一次。
81
+ """
82
+ def compute_phash(image):
83
+ resized = cv2.resize(image, (32, 32), interpolation=cv2.INTER_AREA)
84
+ gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
85
+ dct = cv2.dct(np.float32(gray))
86
+ dct_low = dct[:8, :8]
87
+ med = np.median(dct_low)
88
+ return (dct_low > med).flatten()
89
+
90
+ def compute_sharpness(image):
91
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
92
+ # 使用 Sobel 算子计算梯度
93
+ grad_x = cv2.Sobel(gray, cv2.CV_16S, 1, 0)
94
+ grad_y = cv2.Sobel(gray, cv2.CV_16S, 0, 1)
95
+ # 计算梯度的绝对值和
96
+ sharpness = cv2.mean(np.abs(grad_x) + np.abs(grad_y))[0]
97
+ return sharpness
98
+
99
+ def save_frame(image, frame_count):
100
+ image_name = f'{os.path.splitext(os.path.basename(video_file))[0]}-{frame_count:08d}.jpg'
101
+ image_path = os.path.join(new_folder_path, image_name)
102
+ cv2.imwrite(image_path, image, [cv2.IMWRITE_JPEG_QUALITY, 90])
103
+
104
+ # 打开视频文件
105
+ container = av.open(video_file)
106
+ video = container.streams.video[0]
107
+
108
+ # 尝试启用硬件加速
109
+ try:
110
+ video.codec_context.options = {'hwaccel': 'auto'}
111
+ except Exception as e:
112
+ print(f"无法启用硬件加速: {e}")
113
+ logging.warning(f"无法启用硬件加速: {e}")
114
+
115
+ start_time = time.time()
116
+ frame_count = 0
117
+ saved_count = 0
118
+ sharpness_threshold = 15 # 清晰度阈值
119
+
120
+ reference_image = None
121
+ reference_phash = None
122
+ reference_sharpness = None
123
+ reference_count = 0
124
+
125
+ for frame in tqdm(container.decode(video=0), desc=f"处理视频 {os.path.basename(video_file)}"):
126
+ if frame_count % frame_step != 0:
127
+ frame_count += 1
128
+ continue # 跳过不需要处理的帧
129
+
130
+ image = frame.to_ndarray(format='bgr24')
131
+ phash = compute_phash(image)
132
+ sharpness = compute_sharpness(image)
133
+
134
+ if sharpness < sharpness_threshold:
135
+ frame_count += 1
136
+ continue # 跳过模糊帧
137
+
138
+ if reference_image is None:
139
+ # 初始化参考帧
140
+ reference_image = image
141
+ reference_phash = phash
142
+ reference_sharpness = sharpness
143
+ reference_count = frame_count
144
+ else:
145
+ hamming_dist = np.sum(phash != reference_phash)
146
+ if hamming_dist > 10:
147
+ # 与参考帧差异较大,保存参考���
148
+ save_frame(reference_image, reference_count)
149
+ saved_count += 1
150
+ # 更新参考帧
151
+ reference_image = image
152
+ reference_phash = phash
153
+ reference_sharpness = sharpness
154
+ reference_count = frame_count
155
+ else:
156
+ # 与参考帧相似,比较清晰度
157
+ if sharpness > reference_sharpness:
158
+ # 当前帧更清晰,更新参考帧
159
+ reference_image = image
160
+ reference_phash = phash
161
+ reference_sharpness = sharpness
162
+ reference_count = frame_count
163
+ # 否则,保留原参考帧
164
+
165
+ frame_count += 1
166
+
167
+ # 保存最后的参考帧
168
+ if reference_image is not None:
169
+ save_frame(reference_image, reference_count)
170
+ saved_count += 1
171
+
172
+ total_time = time.time() - start_time
173
+ average_fps = frame_count / total_time if total_time > 0 else 0
174
+ print(f'\n{os.path.basename(video_file)} 处理完成: 总共 {frame_count} 帧, 保存 {saved_count} 帧, 平均 {average_fps:.2f} 帧/秒')
175
+ logging.info(f'{os.path.basename(video_file)} 处理完成: 总共 {frame_count} 帧, 保存 {saved_count} 帧, 平均 {average_fps:.2f} 帧/秒')
176
+
177
+
178
+ def process_images_folder(new_folder_path):
179
+ """
180
+ 处理保存的图像文件,去除相似的重复图片,仅保留最清晰的。
181
+
182
+ 参数:
183
+ new_folder_path (str): 图像文件夹路径。
184
+
185
+ 返回:
186
+ set: 保留的图像文件路径集合。
187
+ """
188
+ def get_image_files(folder_path):
189
+ image_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path)
190
+ if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
191
+ print(f'总共找到 {len(image_files)} 张图片')
192
+ logging.info(f'总共找到 {len(image_files)} 张图片')
193
+ return image_files
194
+
195
+ def process_images(image_files):
196
+ def compute_phash(image):
197
+ resized = cv2.resize(image, (32, 32), interpolation=cv2.INTER_AREA)
198
+ gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
199
+ dct = cv2.dct(np.float32(gray))
200
+ dct_low = dct[:8, :8]
201
+ med = np.median(dct_low)
202
+ return (dct_low > med).flatten()
203
+
204
+ def compute_sharpness(image):
205
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
206
+ return cv2.Laplacian(gray, cv2.CV_64F).var()
207
+
208
+ def process_single_image(image_path):
209
+ image = cv2.imread(image_path)
210
+ if image is None:
211
+ error_message = f"无法读取图像文件 {image_path}"
212
+ print(f"警告:{error_message}")
213
+ logging.warning(error_message)
214
+ return None
215
+ try:
216
+ phash = compute_phash(image)
217
+ sharpness = compute_sharpness(image)
218
+ return image_path, phash, sharpness
219
+ except Exception as e:
220
+ error_message = f"处理图像时出错 {image_path}: {e}"
221
+ print(f"警告:{error_message}")
222
+ logging.warning(error_message)
223
+ return None
224
+
225
+ image_data = {}
226
+ start_time = time.time()
227
+ with ThreadPoolExecutor() as executor:
228
+ futures = [executor.submit(process_single_image, img) for img in image_files]
229
+ for future in tqdm(futures, desc="计算哈希和清晰度", unit="张"):
230
+ result = future.result()
231
+ if result is not None:
232
+ image_path, phash, sharpness = result
233
+ image_data[image_path] = {'phash': phash, 'sharpness': sharpness}
234
+
235
+ elapsed_time = time.time() - start_time
236
+ print(f'\n图片处理完成,耗时 {elapsed_time:.2f} 秒')
237
+ logging.info(f'图片处理完成,耗时 {elapsed_time:.2f} 秒')
238
+ return image_data
239
+
240
+ def compare_images(image_data):
241
+ similar_groups = {}
242
+ hash_buckets = defaultdict(list)
243
+ # 将哈希值转换为字符串,并取前几位作为桶的键
244
+ for image_path, data in image_data.items():
245
+ hash_str = ''.join(data['phash'].astype(int).astype(str))
246
+ bucket_key = hash_str[:16] # 取前16位作为桶的键,可根据需要调整
247
+ hash_buckets[bucket_key].append((image_path, data))
248
+
249
+ total_buckets = len(hash_buckets)
250
+ print(f"总共划分为 {total_buckets} 个哈希桶")
251
+ logging.info(f"总共划分为 {total_buckets} 个哈希桶")
252
+
253
+ # 遍历每个桶,比较桶内的图片
254
+ for bucket_key, bucket in tqdm(hash_buckets.items(), desc="比较哈希桶", unit="桶"):
255
+ paths = [item[0] for item in bucket]
256
+ hashes = np.array([item[1]['phash'] for item in bucket])
257
+ for i in range(len(paths)):
258
+ for j in range(i + 1, len(paths)):
259
+ dist = np.sum(hashes[i] != hashes[j])
260
+ if dist <= 10: # 阈值,可根据需要调整
261
+ similar_groups.setdefault(paths[i], []).append(paths[j])
262
+
263
+ return similar_groups
264
+
265
+ def select_images_to_keep(similar_groups, image_data):
266
+ to_keep = set()
267
+ processed_groups = set()
268
+ for group_key, group in similar_groups.items():
269
+ if group_key in processed_groups:
270
+ continue
271
+ group_with_key = [group_key] + group
272
+ sharpest = max(group_with_key, key=lambda x: image_data[x]['sharpness'])
273
+ to_keep.add(sharpest)
274
+ processed_groups.update(group_with_key)
275
+ # 将不在任何相似组中的图片也加入保留列表
276
+ all_images = set(image_data.keys())
277
+ images_in_groups = set().union(*[set([k] + v) for k, v in similar_groups.items()])
278
+ images_not_in_groups = all_images - images_in_groups
279
+ to_keep.update(images_not_in_groups)
280
+ return to_keep
281
+
282
+ def delete_duplicate_images(similar_groups, to_keep):
283
+ deleted_count = 0
284
+ to_delete = set()
285
+
286
+ # 收集所有需要删除的图片
287
+ for group_key, similar_images in similar_groups.items():
288
+ group_with_key = [group_key] + similar_images
289
+ for image_path in group_with_key:
290
+ if image_path not in to_keep:
291
+ to_delete.add(image_path)
292
+
293
+ total_to_delete = len(to_delete)
294
+
295
+ # 删除图片
296
+ for image_path in tqdm(to_delete, desc="删除重复图片", unit="张"):
297
+ try:
298
+ os.remove(image_path)
299
+ deleted_count += 1
300
+ except Exception as e:
301
+ print(f"\n无法删除 {image_path}: {e}")
302
+ logging.error(f"无法删除 {image_path}: {e}")
303
+
304
+ print(f'\n去重完成,保留 {len(to_keep)} 张图片,成功删除 {deleted_count} 张重复图片')
305
+ logging.info(f'去重完成,保留 {len(to_keep)} 张图片,成功删除 {deleted_count} 张重复图片')
306
+
307
+ return deleted_count
308
+
309
+ # 开始执行去重流程
310
+ image_files = get_image_files(new_folder_path)
311
+ image_data = process_images(image_files)
312
+ similar_groups = compare_images(image_data)
313
+ to_keep = select_images_to_keep(similar_groups, image_data)
314
+ deleted_count = delete_duplicate_images(similar_groups, to_keep)
315
+
316
+
317
+ def waifuc_split(new_folder_path, split_path):
318
+ """
319
+ 使用 waifuc 库对图像进行分割,提取人物部分。
320
+
321
+ 参数:
322
+ new_folder_path (str): 原始图像文件夹路径。
323
+ split_path (str): 分割后图像的保存路径。
324
+ """
325
+ # 直接使用目录路径初始化 LocalSource
326
+ s = LocalSource(new_folder_path)
327
+ s = s.attach(
328
+ PersonSplitAction(), MinSizeFilterAction(300),
329
+ )
330
+ s.export(SaveExporter(split_path, no_meta=True))
331
+
332
+
333
+ def process_split_images(new_folder_path, split_path):
334
+ """
335
+ 将没有检测到人物的原始图像移动到指定的无人文件夹。
336
+
337
+ 参数:
338
+ new_folder_path (str): 原始图像文件夹路径。
339
+ split_path (str): 分割后图像的保存路径。
340
+ """
341
+ nohuman_path = create_output_folder(new_folder_path, "-nohuman")
342
+
343
+ # 获取去重后的原始图片列表
344
+ original_images = [f for f in os.listdir(new_folder_path)
345
+ if os.path.isfile(os.path.join(new_folder_path, f)) and
346
+ f.lower().endswith(('.jpg', '.jpeg', '.png', '.webp'))]
347
+
348
+ split_images = [f for f in os.listdir(split_path)
349
+ if f.lower().endswith(('.jpg', '.jpeg', '.png', '.webp'))]
350
+
351
+ total_images = len(original_images)
352
+ moved_count = 0
353
+
354
+ for original_image in tqdm(original_images, desc="处理无人图片", unit="张"):
355
+ base_name = os.path.splitext(original_image)[0]
356
+ has_person = any(split_image.startswith(base_name + '_person') for split_image in split_images)
357
+
358
+ if not has_person:
359
+ source_path = os.path.join(new_folder_path, original_image)
360
+ dest_path = os.path.join(nohuman_path, original_image)
361
+ try:
362
+ shutil.move(source_path, dest_path)
363
+ moved_count += 1
364
+ except Exception as e:
365
+ print(f"\n无法移动 {source_path}: {e}")
366
+ logging.error(f"无法移动 {source_path}: {e}")
367
+
368
+ print(f'\n处理完成。总共处理 {total_images} 张图片, 移动了 {moved_count} 张无人图片到 {nohuman_path}')
369
+ logging.info(f'处理完成。总共处理 {total_images} 张图片, 移动了 {moved_count} 张无人图片到 {nohuman_path}')
370
+
371
+
372
+ def main():
373
+ """
374
+ 主函数,执行整个处理流程。
375
+ """
376
+ folder_path = select_folder()
377
+ if not folder_path:
378
+ print("未选择文件夹,程序退出。")
379
+ logging.error("未选择文件夹,程序退出。")
380
+ return
381
+
382
+ video_files = find_video_files(folder_path)
383
+ if not video_files:
384
+ print("所选文件夹中未找到视频文件,程序退出。")
385
+ logging.error("所选文件夹中未找到视频文件,程序退出。")
386
+ return
387
+
388
+ # 创建保存提取帧的文件夹
389
+ new_folder_path = create_output_folder(folder_path, "-Eng_SS")
390
+
391
+ # 处理每个视频文件
392
+ for video_file in video_files:
393
+ print(f"开始处理视频文件: {video_file}")
394
+ logging.info(f"开始处理视频文件: {video_file}")
395
+ process_video(video_file, new_folder_path, frame_step=5) # 设置帧步长
396
+
397
+ # 去除相似的重复图片(第一次)
398
+ process_images_folder(new_folder_path)
399
+ # 去除相似的重复图片(第二次)
400
+ process_images_folder(new_folder_path)
401
+
402
+ # 创建保存分割后图像的文件夹
403
+ split_path = create_output_folder(new_folder_path, "-split")
404
+
405
+ # 使用 waifuc 库进行人物分割
406
+ waifuc_split(new_folder_path, split_path)
407
+
408
+ # 移动没有检测到人物的图像到无人文件夹
409
+ process_split_images(new_folder_path, split_path)
410
+
411
+
412
+ if __name__ == "__main__":
413
+ main()