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