-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyMuPDF_Finally4.py
More file actions
1671 lines (1370 loc) · 70.4 KB
/
PyMuPDF_Finally4.py
File metadata and controls
1671 lines (1370 loc) · 70.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import random
import time
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import numpy as np
import datetime
from typing import Tuple, Optional
import threading
import sys
import re
import cv2
import textwrap
import re
print("🌟 === BBOX升级版文字特效渲染工具 === 🌟")
# --- 1. 升级配置区 ---
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FONTS_DIR = os.path.join(BASE_DIR, 'fonts')
INPUT_IMAGES_DIR = os.path.join(BASE_DIR, 'input_images')
BBOX_IMAGES_DIR = os.path.join(BASE_DIR, 'bbox_images') # 新增bbox目录
OUTPUT_DIR = os.path.join(BASE_DIR, 'output444')
# --- 2. 长句子文本库(纯英文) ---
LONG_TEXT_SAMPLES = [
# 励志名言句子
"The future belongs to those who believe in the beauty of their dreams",
"Success is not final, failure is not fatal, it is the courage to continue that counts",
"In the middle of difficulty lies opportunity waiting to be discovered",
"The only way to do great work is to love what you do with passion",
"Innovation distinguishes between a leader and a follower in every field",
"Your limitation is only your imagination when you dare to dream big",
"Great things never come from comfort zones, so step out and explore",
"Dream it, wish it, do it with determination and never give up",
"The harder you work for something, the greater you will feel when you achieve it",
"Success doesn't just find you, you have to go out and get it",
# 科幻电影经典台词
"May the Force be with you always, young Jedi warrior",
"I'll be back to save humanity from the machines",
"The Matrix has you, but you can choose the red pill",
"Resistance is futile, you will be assimilated into the collective",
"Live long and prosper in the final frontier of space",
"Houston, we have a problem with our spacecraft systems",
"Space, the final frontier where no one has gone before",
"These aren't the droids you're looking for, move along",
"Welcome to the real world, it's not what it seems",
"The needs of the many outweigh the needs of the few",
# 赛博朋克风格句子
"In the neon-lit streets of Neo Tokyo, hackers rule the digital underground",
"Cybernetic enhancements blur the line between human and machine consciousness",
"Data streams flow like rivers of light through the virtual reality matrix",
"Corporate megacities rise above the smog where augmented humans survive",
"Neural interfaces connect minds to the global information network",
"Synthetic dreams download directly into sleeping cyber-enhanced brains",
"Digital ghosts haunt the abandoned servers of forgotten online worlds",
"Chrome and flesh merge in the shadowy backstreets of tomorrow",
"Holographic advertisements flicker in the perpetual rain of acid storms",
"Memory chips store lifetimes of experience in quantum storage arrays",
# 游戏相关段落
"Player one, prepare for the ultimate boss battle that will test all your skills",
"Achievement unlocked: Master of the Digital Realm with infinite possibilities ahead",
"Game over is not the end, it's just another chance to level up",
"In this virtual world, every quest leads to greater adventures and treasures",
"The legendary sword awaits the chosen hero in the depths of the dungeon",
"Multiplayer chaos erupts as teams clash in epic battles across alien worlds",
"Loading next level, where new challenges and mysteries await brave explorers",
"High score achieved through dedication, practice, and never surrendering to defeat",
"The final countdown begins as players race against time to save the universe",
"Virtual reality becomes indistinguishable from actual reality in the metaverse",
# 音乐和艺术主题
"Music is the universal language that speaks to every soul across all cultures",
"Colors dance across the canvas as the artist brings imagination to vivid life",
"Rhythm and melody combine to create symphonies that transcend time and space",
"Digital art emerges from pixels and code to inspire the next generation",
"The stage lights dim as performers prepare to transport audiences to other worlds",
"Sound waves ripple through the air carrying emotions that words cannot express",
"Creative inspiration strikes like lightning, illuminating the path to artistic greatness",
"The gallery walls showcase masterpieces that challenge perception and reality",
"Electronic beats pulse through the night club as dancers lose themselves",
"Artistic vision transforms ordinary materials into extraordinary expressions of beauty",
# 技术和创新主题
"Artificial intelligence awakens to consciousness in the quantum computing laboratory",
"Blockchain technology revolutionizes trust in the decentralized digital economy",
"Machine learning algorithms evolve beyond their original programming parameters",
"Virtual reality headsets transport users to impossible worlds of infinite wonder",
"Quantum entanglement enables instantaneous communication across vast cosmic distances",
"Nanotechnology assembles materials atom by atom with precision beyond imagination",
"Genetic engineering unlocks the secrets hidden within the human genome",
"Renewable energy harvests power from wind, solar, and geothermal sources",
"3D printing materializes objects from digital designs into physical reality",
"Cloud computing connects global networks in seamless information exchange",
]
##智能换行
def smart_fit_text_to_bbox(text, font, bbox, line_spacing=1.2):
"""
🧠 超级智能的BBOX文本自适应函数
自动换行 + 字号调整 + 完美居中
"""
x1, y1, x2, y2 = bbox
bbox_width = x2 - x1
bbox_height = y2 - y1
# 留边距,防止贴边
margin_x = int(bbox_width * 0.05) # 5% 水平边距
margin_y = int(bbox_height * 0.05) # 5% 垂直边距
available_width = bbox_width - 2 * margin_x
available_height = bbox_height - 2 * margin_y
print(f"📦 BBOX区域: {bbox_width}x{bbox_height}, 可用区域: {available_width}x{available_height}")
# 创建临时绘制对象用于测量
temp_img = Image.new('RGB', (bbox_width * 2, bbox_height * 2))
temp_draw = ImageDraw.Draw(temp_img)
# 获取字体基本信息
sample_bbox = temp_draw.textbbox((0, 0), "Ay", font=font)
font_height = sample_bbox[3] - sample_bbox[1]
line_height = int(font_height * line_spacing)
print(f"📏 字体高度: {font_height}px, 行高: {line_height}px")
def measure_text_width(text_line):
"""测量单行文本宽度"""
bbox = temp_draw.textbbox((0, 0), text_line, font=font)
return bbox[2] - bbox[0]
def wrap_text_smart(text, max_width):
"""智能文本换行"""
words = text.split()
lines = []
current_line = []
for word in words:
# 测试加入这个词后的宽度
test_line = ' '.join(current_line + [word])
test_width = measure_text_width(test_line)
if test_width <= max_width:
# 能放下,加入当前行
current_line.append(word)
else:
# 放不下了
if current_line:
# 保存当前行,开始新行
lines.append(' '.join(current_line))
current_line = [word]
else:
# 单词太长,强制加入
lines.append(word)
current_line = []
# 处理最后一行
if current_line:
lines.append(' '.join(current_line))
return lines
# 首先尝试原始字体大小
wrapped_lines = wrap_text_smart(text, available_width)
total_text_height = len(wrapped_lines) * line_height
print(f"📝 换行结果: {len(wrapped_lines)} 行, 总高度: {total_text_height}px")
# 检查是否超出高度限制
if total_text_height > available_height:
print("⚠️ 文本太高,尝试缩小字号...")
# 这里可以实现字号自适应,暂时先警告
print(f" 可用高度: {available_height}px, 需要高度: {total_text_height}px")
# 计算垂直居中位置
start_y = y1 + margin_y + max(0, (available_height - total_text_height) // 2)
# 计算每行的水平居中位置
positioned_lines = []
for i, line in enumerate(wrapped_lines):
line_width = measure_text_width(line)
# 水平居中
line_x = x1 + margin_x + (available_width - line_width) // 2
line_y = start_y + i * line_height
positioned_lines.append({
'text': line,
'position': (line_x, line_y),
'width': line_width
})
print(f" 第{i+1}行: '{line}' -> ({line_x}, {line_y})")
return positioned_lines
def render_multiline_text_effect(effect_layer, positioned_lines, font, effect, effect_key):
"""
🎨 渲染多行文本特效
支持所有特效类型的多行渲染
"""
print(f"🎨 渲染多行特效: {effect_key}")
if effect_key.startswith('neon_'):
# 霓虹特效多行渲染
for line_data in positioned_lines:
text = line_data['text']
position = line_data['position']
# 渲染霓虹发光层
glow_sizes = [30, 25, 20, 15, 10, 5]
for i, size in enumerate(glow_sizes):
glow_img = Image.new('RGBA', effect_layer.size, (0, 0, 0, 0))
glow_draw = ImageDraw.Draw(glow_img)
alpha = max(30, 150 - i * 20)
glow_color = tuple(min(255, c + 50) for c in effect.color) + (alpha,)
glow_draw.text(position, text, font=font, fill=glow_color)
blur_radius = size / 5.0
glow_img = glow_img.filter(ImageFilter.GaussianBlur(radius=blur_radius))
effect_layer = Image.alpha_composite(effect_layer, glow_img)
# 渲染主文本
main_draw = ImageDraw.Draw(effect_layer)
bright_color = tuple(min(255, c + 100) for c in effect.color) + (255,)
main_draw.text(position, text, font=font, fill=bright_color)
elif effect_key == 'fire_text':
# 火焰特效多行渲染
fire_layers = [
((255, 0, 0, 60), 25),
((255, 69, 0, 80), 20),
((255, 140, 0, 100), 15),
((255, 215, 0, 120), 10),
((255, 255, 200, 140), 5),
]
for line_data in positioned_lines:
text = line_data['text']
position = line_data['position']
for (color, blur_size) in fire_layers:
fire_img = Image.new('RGBA', effect_layer.size, (0, 0, 0, 0))
fire_draw = ImageDraw.Draw(fire_img)
fire_draw.text(position, text, font=font, fill=color)
if blur_size > 0:
fire_img = fire_img.filter(ImageFilter.GaussianBlur(radius=blur_size/4))
effect_layer = Image.alpha_composite(effect_layer, fire_img)
# 核心文本
core_draw = ImageDraw.Draw(effect_layer)
core_draw.text(position, text, font=font, fill=(255, 255, 255, 255))
elif effect_key == 'cyberpunk':
# 赛博朋克特效多行渲染
cyber_green = (0, 255, 65)
glow_sizes = [35, 30, 25, 20, 15, 10, 5]
for line_data in positioned_lines:
text = line_data['text']
position = line_data['position']
for i, size in enumerate(glow_sizes):
glow_img = Image.new('RGBA', effect_layer.size, (0, 0, 0, 0))
glow_draw = ImageDraw.Draw(glow_img)
alpha = max(40, 200 - i * 25)
glow_color = cyber_green + (alpha,)
glow_draw.text(position, text, font=font, fill=glow_color)
if size > 0:
glow_img = glow_img.filter(ImageFilter.GaussianBlur(radius=size/6))
effect_layer = Image.alpha_composite(effect_layer, glow_img)
# 核心文本
core_draw = ImageDraw.Draw(effect_layer)
core_draw.text(position, text, font=font, fill=(0, 255, 65, 255))
else:
# 其他特效:简单多行渲染
main_draw = ImageDraw.Draw(effect_layer)
for line_data in positioned_lines:
text = line_data['text']
position = line_data['position']
if effect_key == 'rainbow':
# 彩虹特效需要特殊处理
rainbow_colors = [
(255, 0, 0), (255, 127, 0), (255, 255, 0), (0, 255, 0),
(0, 255, 255), (0, 0, 255), (148, 0, 211),
]
x_offset = 0
for i, char in enumerate(text):
if char.strip():
color = rainbow_colors[i % len(rainbow_colors)]
bbox = main_draw.textbbox((0, 0), char, font=font)
char_width = bbox[2] - bbox[0]
main_draw.text((position[0] + x_offset, position[1]), char,
font=font, fill=color + (255,))
x_offset += char_width
else:
bbox = main_draw.textbbox((0, 0), ' ', font=font)
x_offset += bbox[2] - bbox[0]
else:
# 默认白色文本
main_draw.text(position, text, font=font, fill=(255, 255, 255, 255))
return effect_layer
# --- 3. 彻底修复的输入函数 ---
def get_user_input_fixed(prompt, timeout=5, default=None, wait_for_text=False):
"""彻底修复回车问题的输入函数"""
print(prompt, end='', flush=True)
if wait_for_text:
# 文本输入模式:允许多次尝试,彻底处理回车问题
while True:
try:
user_input = input().strip()
# 如果输入不为空且不是纯空格,返回输入
if user_input and user_input.replace(' ', ''):
print(f"✅ 输入成功: '{user_input[:50]}{'...' if len(user_input) > 50 else ''}'")
return user_input
# 如果是空输入,询问是否要随机
print("💡 输入为空。再次输入文本,或直接回车使用随机文本: ", end='', flush=True)
confirm = input().strip()
if confirm and confirm.replace(' ', ''):
print(f"✅ 输入成功: '{confirm[:50]}{'...' if len(confirm) > 50 else ''}'")
return confirm
else:
print("🎲 使用随机文本")
return default
except (KeyboardInterrupt, EOFError):
print("\n⚠️ 输入被中断,使用随机文本")
return default
else:
# 选择模式:使用简化的超时机制
try:
import select
import sys
# 检查是否有输入可用(仅Unix/Linux)
if hasattr(select, 'select'):
ready, _, _ = select.select([sys.stdin], [], [], timeout)
if ready:
user_input = input().strip()
return user_input if user_input else default
else:
print(f"\n⏱️ {timeout}秒超时,使用默认选择")
return default
else:
# Windows兼容模式
user_input = input().strip()
return user_input if user_input else default
except:
# 简单fallback
try:
user_input = input().strip()
return user_input if user_input else default
except:
return default
# --- 4. BBOX检测功能 ---
def detect_red_bbox_improved(image_path):
"""增强版红框检测,更精确的HSV阈值和边缘检测"""
try:
image = cv2.imread(image_path)
if image is None:
print(f"❌ 无法读取图像: {image_path}")
return None
# 转换到HSV色彩空间
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 使用更精确的红色范围
lower_red1 = np.array([0, 70, 70]) # 更高的饱和度和亮度阈值
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([165, 70, 70]) # 调整色相范围
upper_red2 = np.array([180, 255, 255])
# 创建红色掩码
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
red_mask = cv2.bitwise_or(mask1, mask2)
# 边缘增强 - 先进行轻微高斯模糊,然后使用Canny边缘检测
blurred = cv2.GaussianBlur(red_mask, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)
# 寻找轮廓 - 使用CHAIN_APPROX_TC89_KCOS更好地逼近轮廓
contours, _ = cv2.findContours(red_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)
if not contours:
return None
# 找到最像矩形的轮廓,而不只是最大的
best_contour = None
best_rect_score = 0
for contour in contours:
# 忽略太小的轮廓
area = cv2.contourArea(contour)
if area < 500: # 设置最小面积阈值
continue
# 获取最小外接矩形
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
rect_area = cv2.contourArea(box)
# 计算轮廓与矩形的相似度
similarity = area / rect_area if rect_area > 0 else 0
# 更新最佳矩形
if similarity > best_rect_score:
best_rect_score = similarity
best_contour = contour
if best_contour is None:
return None
# 获取边界矩形
x, y, w, h = cv2.boundingRect(best_contour)
# 验证矩形尺寸和形状
if w < 20 or h < 20 or max(w, h) / min(w, h) > 10: # 忽略太小或比例极端的矩形
return None
bbox = (x, y, x + w, y + h)
print(f"✅ 检测到红色bbox: x1={x}, y1={y}, x2={x+w}, y2={y+h}, 宽度={w}, 高度={h}")
# 保存标记图像用于调试
debug_img = image.copy()
cv2.rectangle(debug_img, (x, y), (x+w, y+h), (0, 255, 0), 2) # 绿色框显示检测结果
debug_path = image_path.replace('.', '_debug.')
cv2.imwrite(debug_path, debug_img)
print(f"📊 调试图像已保存: {os.path.basename(debug_path)}")
return bbox
except Exception as e:
print(f"❌ bbox检测失败: {str(e)}")
return None
def find_matching_bbox_image(background_image_name):
"""根据背景图名称查找对应的bbox图像"""
if not os.path.exists(BBOX_IMAGES_DIR):
return None
# 获取背景图的基础名称(无扩展名)
base_name = os.path.splitext(background_image_name)[0]
# 在bbox目录中查找同名文件
for ext in ['.png', '.jpg', '.jpeg', '.bmp', '.webp']:
bbox_path = os.path.join(BBOX_IMAGES_DIR, base_name + ext)
if os.path.exists(bbox_path):
print(f"✅ 找到对应的bbox图像: {base_name + ext}")
return bbox_path
print(f"⚠️ 未找到对应的bbox图像: {base_name}")
return None
def fit_text_to_bbox(text, font, bbox):
"""将文本适配到bbox区域内"""
x1, y1, x2, y2 = bbox
bbox_width = x2 - x1
bbox_height = y2 - y1
# 创建临时图像测量文本
temp_img = Image.new('RGB', (bbox_width * 2, bbox_height * 2))
temp_draw = ImageDraw.Draw(temp_img)
# 测量单行文本尺寸
text_bbox = temp_draw.textbbox((0, 0), text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
# 如果文本能够单行放下
if text_width <= bbox_width * 0.9: # 留10%边距
# 计算居中位置
text_x = x1 + (bbox_width - text_width) // 2
text_y = y1 + (bbox_height - text_height) // 2
return (text_x, text_y), False # False表示不需要换行
# 需要换行处理
words = text.split()
lines = []
current_line = []
for word in words:
test_line = ' '.join(current_line + [word])
test_bbox = temp_draw.textbbox((0, 0), test_line, font=font)
test_width = test_bbox[2] - test_bbox[0]
if test_width <= bbox_width * 0.9:
current_line.append(word)
else:
if current_line: # 如果当前行有内容
lines.append(' '.join(current_line))
current_line = [word]
else: # 单个词都太长,强制加入
lines.append(word)
current_line = []
if current_line:
lines.append(' '.join(current_line))
# 计算多行文本的起始位置
total_text_height = len(lines) * text_height
start_y = y1 + max(0, (bbox_height - total_text_height) // 2)
return (x1 + bbox_width * 0.05, start_y), lines # 返回位置和行列表
# --- 5. 特效类定义(保持不变) ---
class TextEffect:
def __init__(self, name: str, description: str):
self.name = name
self.description = description
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
"""应用特效的基类方法,新增bbox参数"""
raise NotImplementedError
# 更新 NeonEffect 类
class NeonEffect(TextEffect):
def __init__(self, color: Tuple[int, int, int], name: str):
super().__init__(name, f"霓虹发光效果 - {name}")
self.color = color
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
effect_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
if bbox:
# BBOX模式:使用智能多行渲染
positioned_lines = smart_fit_text_to_bbox(text, font, bbox)
effect_layer = render_multiline_text_effect(effect_layer, positioned_lines, font, self, 'neon_' + self.name.lower())
else:
# 简单模式:单行渲染
display_text = ' '.join(text) if isinstance(text, list) else text
self._render_neon_text(effect_layer, display_text, position, font)
result = image.convert('RGBA')
result = Image.alpha_composite(result, effect_layer)
return result
def _render_neon_text(self, effect_layer, text, position, font):
"""单行霓虹渲染(保持兼容性)"""
glow_sizes = [30, 25, 20, 15, 10, 5]
for i, size in enumerate(glow_sizes):
glow_img = Image.new('RGBA', effect_layer.size, (0, 0, 0, 0))
glow_draw = ImageDraw.Draw(glow_img)
alpha = max(30, 150 - i * 20)
glow_color = tuple(min(255, c + 50) for c in self.color) + (alpha,)
glow_draw.text(position, text, font=font, fill=glow_color)
blur_radius = size / 5.0
glow_img = glow_img.filter(ImageFilter.GaussianBlur(radius=blur_radius))
effect_layer = Image.alpha_composite(effect_layer, glow_img)
main_draw = ImageDraw.Draw(effect_layer)
bright_color = tuple(min(255, c + 100) for c in self.color) + (255,)
main_draw.text(position, text, font=font, fill=bright_color)
# 其他特效类似地添加bbox支持...
class FireEffect(TextEffect):
def __init__(self):
super().__init__("火焰文字", "真实火焰燃烧效果")
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
effect_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
fire_layers = [
((255, 0, 0, 60), 25),
((255, 69, 0, 80), 20),
((255, 140, 0, 100), 15),
((255, 215, 0, 120), 10),
((255, 255, 200, 140), 5),
]
# 处理多行文本
if isinstance(text, list):
temp_bbox = ImageDraw.Draw(effect_layer).textbbox((0, 0), "Ay", font=font)
line_height = temp_bbox[3] - temp_bbox[1] + 5
for i, line in enumerate(text):
line_pos = (position[0], position[1] + i * line_height)
self._render_fire_text(effect_layer, line, line_pos, font, fire_layers)
else:
self._render_fire_text(effect_layer, text, position, font, fire_layers)
result = image.convert('RGBA')
return Image.alpha_composite(result, effect_layer)
def _render_fire_text(self, effect_layer, text, position, font, fire_layers):
"""渲染火焰文本"""
for (color, blur_size) in fire_layers:
fire_img = Image.new('RGBA', effect_layer.size, (0, 0, 0, 0))
fire_draw = ImageDraw.Draw(fire_img)
fire_draw.text(position, text, font=font, fill=color)
if blur_size > 0:
fire_img = fire_img.filter(ImageFilter.GaussianBlur(radius=blur_size/4))
effect_layer = Image.alpha_composite(effect_layer, fire_img)
core_draw = ImageDraw.Draw(effect_layer)
core_draw.text(position, text, font=font, fill=(255, 255, 255, 255))
# 简化其他特效类(与之前相同,但添加bbox参数支持)
class IceEffect(TextEffect):
def __init__(self):
super().__init__("冰霜文字", "寒冰水晶效果")
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
# 基本实现(可按需扩展多行支持)
effect_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
ice_layers = [
((173, 216, 230, 40), 20),
((135, 206, 235, 60), 15),
((100, 149, 237, 80), 10),
((70, 130, 180, 100), 5),
]
display_text = ' '.join(text) if isinstance(text, list) else text
for (color, blur_size) in ice_layers:
ice_img = Image.new('RGBA', image.size, (0, 0, 0, 0))
ice_draw = ImageDraw.Draw(ice_img)
ice_draw.text(position, display_text, font=font, fill=color)
if blur_size > 0:
ice_img = ice_img.filter(ImageFilter.GaussianBlur(radius=blur_size/4))
effect_layer = Image.alpha_composite(effect_layer, ice_img)
core_draw = ImageDraw.Draw(effect_layer)
core_draw.text(position, display_text, font=font, fill=(220, 248, 255, 255))
result = image.convert('RGBA')
return Image.alpha_composite(result, effect_layer)
class GoldEffect(TextEffect):
def __init__(self):
super().__init__("金色文字", "华丽金色效果")
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
effect_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
display_text = ' '.join(text) if isinstance(text, list) else text
shadow_pos = (position[0] + 4, position[1] + 4)
shadow_draw = ImageDraw.Draw(effect_layer)
shadow_draw.text(shadow_pos, display_text, font=font, fill=(139, 69, 19, 180))
effect_layer = effect_layer.filter(ImageFilter.GaussianBlur(radius=3))
glow_draw = ImageDraw.Draw(effect_layer)
glow_draw.text(position, display_text, font=font, fill=(255, 215, 0, 200))
highlight_draw = ImageDraw.Draw(effect_layer)
highlight_draw.text(position, display_text, font=font, fill=(255, 255, 200, 255))
result = image.convert('RGBA')
return Image.alpha_composite(result, effect_layer)
class ShadowEffect(TextEffect):
def __init__(self, shadow_color: Tuple[int, int, int] = (0, 0, 0),
offset: Tuple[int, int] = (6, 6), blur_radius: int = 4):
super().__init__("阴影文字", "真实投影效果")
self.shadow_color = shadow_color
self.offset = offset
self.blur_radius = blur_radius
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
effect_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
display_text = ' '.join(text) if isinstance(text, list) else text
shadow_pos = (position[0] + self.offset[0], position[1] + self.offset[1])
shadow_draw = ImageDraw.Draw(effect_layer)
shadow_draw.text(shadow_pos, display_text, font=font, fill=self.shadow_color + (150,))
if self.blur_radius > 0:
effect_layer = effect_layer.filter(ImageFilter.GaussianBlur(radius=self.blur_radius))
main_draw = ImageDraw.Draw(effect_layer)
main_draw.text(position, display_text, font=font, fill=(255, 255, 255, 255))
result = image.convert('RGBA')
return Image.alpha_composite(result, effect_layer)
class RainbowEffect(TextEffect):
def __init__(self):
super().__init__("彩虹文字", "七彩渐变效果")
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
effect_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
effect_draw = ImageDraw.Draw(effect_layer)
display_text = ' '.join(text) if isinstance(text, list) else text
rainbow_colors = [
(255, 0, 0), (255, 127, 0), (255, 255, 0), (0, 255, 0),
(0, 255, 255), (0, 0, 255), (148, 0, 211),
]
for color in rainbow_colors:
glow_img = Image.new('RGBA', image.size, (0, 0, 0, 0))
glow_draw = ImageDraw.Draw(glow_img)
glow_draw.text(position, display_text, font=font, fill=color + (60,))
glow_img = glow_img.filter(ImageFilter.GaussianBlur(radius=8))
effect_layer = Image.alpha_composite(effect_layer, glow_img)
x_offset = 0
for i, char in enumerate(display_text):
if char.strip():
color = rainbow_colors[i % len(rainbow_colors)]
bbox = effect_draw.textbbox((0, 0), char, font=font)
char_width = bbox[2] - bbox[0]
effect_draw.text((position[0] + x_offset, position[1]), char,
font=font, fill=color + (255,))
x_offset += char_width
else:
bbox = effect_draw.textbbox((0, 0), ' ', font=font)
x_offset += bbox[2] - bbox[0]
result = image.convert('RGBA')
return Image.alpha_composite(result, effect_layer)
class EmbossEffect(TextEffect):
def __init__(self):
super().__init__("浮雕效果", "立体浮雕文字")
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
effect_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
effect_draw = ImageDraw.Draw(effect_layer)
display_text = ' '.join(text) if isinstance(text, list) else text
shadow_pos = (position[0] + 2, position[1] + 2)
effect_draw.text(shadow_pos, display_text, font=font, fill=(0, 0, 0, 120))
highlight_pos = (position[0] - 1, position[1] - 1)
effect_draw.text(highlight_pos, display_text, font=font, fill=(255, 255, 255, 180))
effect_draw.text(position, display_text, font=font, fill=(160, 160, 160, 255))
result = image.convert('RGBA')
return Image.alpha_composite(result, effect_layer)
class CyberpunkEffect(TextEffect):
def __init__(self):
super().__init__("赛博朋克", "科幻电子发光")
def apply(self, image: Image.Image, text: str, position: Tuple[int, int],
font: ImageFont.ImageFont, bbox: Optional[Tuple[int, int, int, int]] = None) -> Image.Image:
effect_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
display_text = ' '.join(text) if isinstance(text, list) else text
cyber_green = (0, 255, 65)
glow_sizes = [35, 30, 25, 20, 15, 10, 5]
for i, size in enumerate(glow_sizes):
glow_img = Image.new('RGBA', image.size, (0, 0, 0, 0))
glow_draw = ImageDraw.Draw(glow_img)
alpha = max(40, 200 - i * 25)
glow_color = cyber_green + (alpha,)
glow_draw.text(position, display_text, font=font, fill=glow_color)
if size > 0:
glow_img = glow_img.filter(ImageFilter.GaussianBlur(radius=size/6))
effect_layer = Image.alpha_composite(effect_layer, glow_img)
core_draw = ImageDraw.Draw(effect_layer)
core_draw.text(position, display_text, font=font, fill=(0, 255, 65, 255))
result = image.convert('RGBA')
return Image.alpha_composite(result, effect_layer)
# --- 6. 特效集合 ---
TEXT_EFFECTS = {
'neon_blue': NeonEffect((0, 255, 255), "霓虹蓝光"),
'neon_pink': NeonEffect((255, 20, 147), "霓虹粉光"),
'neon_green': NeonEffect((57, 255, 20), "霓虹绿光"),
'neon_purple': NeonEffect((148, 0, 211), "霓虹紫光"),
'fire_text': FireEffect(),
'ice_text': IceEffect(),
'gold_text': GoldEffect(),
'shadow_black': ShadowEffect((0, 0, 0), (8, 8), 5),
'shadow_colored': ShadowEffect((128, 0, 128), (10, 10), 6),
'rainbow': RainbowEffect(),
'emboss': EmbossEffect(),
'cyberpunk': CyberpunkEffect(),
}
# --- 7. 加载函数 ---
def load_available_fonts():
font_files = []
if os.path.isdir(FONTS_DIR):
font_files = [f for f in os.listdir(FONTS_DIR) if f.lower().endswith(('.ttf', '.otf'))]
if not font_files:
print(f"⚠️ 警告: '{FONTS_DIR}' 文件夹未找到或为空。")
return []
else:
print(f"✅ 找到 {len(font_files)} 个字体文件")
return font_files
def load_available_images():
image_files = []
if os.path.isdir(INPUT_IMAGES_DIR):
image_files = [f for f in os.listdir(INPUT_IMAGES_DIR)
if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.webp'))]
if not image_files:
print(f"⚠️ 警告: '{INPUT_IMAGES_DIR}' 文件夹未找到或为空。")
return []
else:
print(f"✅ 找到 {len(image_files)} 个图像文件")
return image_files
def load_bbox_images():
"""加载bbox标注图像"""
bbox_files = []
if os.path.isdir(BBOX_IMAGES_DIR):
bbox_files = [f for f in os.listdir(BBOX_IMAGES_DIR)
if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.webp'))]
print(f"✅ 找到 {len(bbox_files)} 个bbox标注图像")
else:
print(f"⚠️ bbox目录不存在: {BBOX_IMAGES_DIR}")
return bbox_files
AVAILABLE_FONTS = load_available_fonts()
AVAILABLE_IMAGES = load_available_images()
BBOX_IMAGES = load_bbox_images()
FONT_SIZE_OPTIONS = [24, 32, 40, 48, 56, 64]
LAYOUT_POSITIONS = {
'top-left': lambda w, h: (int(w * 0.1), int(h * 0.1)),
'top-center': lambda w, h: (int(w * 0.5), int(h * 0.1)),
'top-right': lambda w, h: (int(w * 0.9), int(h * 0.1)),
'center-left': lambda w, h: (int(w * 0.1), int(h * 0.5)),
'center': lambda w, h: (int(w * 0.5), int(h * 0.5)),
'center-right': lambda w, h: (int(w * 0.9), int(h * 0.5)),
'bottom-left': lambda w, h: (int(w * 0.1), int(h * 0.85)),
'bottom-center': lambda w, h: (int(w * 0.5), int(h * 0.85)),
'bottom-right': lambda w, h: (int(w * 0.9), int(h * 0.85)),
}
def smart_position_text(image_size, text, font, position_key):
"""智能调整文本位置,确保不溢出(简单模式用)"""
width, height = image_size
temp_img = Image.new('RGB', (1, 1))
temp_draw = ImageDraw.Draw(temp_img)
bbox = temp_draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
margin_x = max(20, text_width * 0.05)
margin_y = max(20, text_height * 0.05)
position_func = LAYOUT_POSITIONS.get(position_key, LAYOUT_POSITIONS['center'])
base_x, base_y = position_func(width, height)
if 'center' in position_key:
if 'top' in position_key or 'bottom' in position_key:
x = base_x - text_width // 2
elif 'left' in position_key or 'right' in position_key:
x = base_x
if 'right' in position_key:
x = base_x - text_width
else:
x = base_x - text_width // 2
y = base_y
if 'center' == position_key:
y = base_y - text_height // 2
else:
x, y = base_x, base_y
if 'right' in position_key:
x = base_x - text_width
if 'bottom' in position_key:
y = base_y - text_height
x = max(margin_x, min(x, width - text_width - margin_x))
y = max(margin_y, min(y, height - text_height - margin_y))
return (int(x), int(y))
# --- 8. A/B文本变化生成器(保持不变) ---
def generate_text_variations(original_text, variation_type="random"):
"""生成A/B对比的文本变化"""
words = original_text.split()
if variation_type == "insert" or (variation_type == "random" and random.choice([True, False, False, False, False])):
# 文本插入:在随机位置插入词汇
insert_words = ["amazing", "incredible", "fantastic", "awesome", "brilliant", "spectacular", "magnificent", "extraordinary"]
insert_word = random.choice(insert_words)
insert_pos = random.randint(0, len(words))
new_words = words[:insert_pos] + [insert_word] + words[insert_pos:]
return " ".join(new_words), "INSERT"
elif variation_type == "delete" or (variation_type == "random" and len(words) > 5 and random.choice([True, False, False, False, False])):
# 文本删除:删除1-2个词
delete_count = min(2, max(1, len(words) // 5))
new_words = words[:]
for _ in range(delete_count):
if len(new_words) > 3:
del_pos = random.randint(1, len(new_words) - 2) # 不删除首尾词
new_words.pop(del_pos)
return " ".join(new_words), "DELETE"
elif variation_type == "replace" or (variation_type == "random" and random.choice([True, False, False])):
# 文本替换:替换1-2个词汇
replacement_dict = {
"future": "tomorrow", "past": "yesterday", "present": "today",
"great": "amazing", "good": "excellent", "bad": "terrible",
"big": "huge", "small": "tiny", "fast": "quick", "slow": "steady",
"beautiful": "gorgeous", "ugly": "hideous", "smart": "brilliant",
"strong": "powerful", "weak": "fragile", "happy": "joyful",
"sad": "sorrowful", "love": "adore", "hate": "despise",
"world": "universe", "earth": "planet", "space": "cosmos",
"technology": "innovation", "computer": "machine", "digital": "electronic",
"human": "person", "people": "individuals", "life": "existence"
}
new_words = words[:]
replaced = False
# 尝试替换已知词汇
for i, word in enumerate(new_words):
clean_word = word.lower().strip('.,!?";:')
if clean_word in replacement_dict:
# 保持原有的大小写和标点
replacement = replacement_dict[clean_word]
if word[0].isupper():
replacement = replacement.capitalize()
# 保持标点符号
punctuation = ''.join(c for c in word if not c.isalpha())
new_words[i] = replacement + punctuation
replaced = True
break
# 如果没有找到可替换的词,随机替换一个
if not replaced and len(words) > 2:
replace_pos = random.randint(1, len(words) - 2)
synonyms = ["incredible", "amazing", "fantastic", "brilliant", "spectacular", "remarkable", "outstanding", "exceptional"]
new_words[replace_pos] = random.choice(synonyms)
return " ".join(new_words), "REPLACE"
elif variation_type == "move" or (variation_type == "random" and len(words) > 4 and random.choice([True, False, False, False])):
# 文本移动:移动词汇位置
if len(words) >= 4:
new_words = words[:]
# 随机选择要移动的词汇段
move_start = random.randint(0, len(words) - 2)
move_end = min(move_start + random.randint(1, 2), len(words))
moved_segment = new_words[move_start:move_end]
# 从原位置删除
del new_words[move_start:move_end]
# 插入到新位置
new_pos = random.randint(0, len(new_words))
new_words = new_words[:new_pos] + moved_segment + new_words[new_pos:]
return " ".join(new_words), "MOVE"
# 默认情况:随机选择一种变化
variation_types = ["insert", "replace"]