forked from shadowcz007/comfyui-mixlab-nodes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageNode.py
3488 lines (2671 loc) · 107 KB
/
ImageNode.py
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 numpy as np
import requests
import torch
import torchvision.transforms.v2 as T
# from PIL import Image, ImageDraw
from PIL import Image, ImageOps,ImageFilter,ImageEnhance,ImageDraw,ImageSequence, ImageFont
from PIL.PngImagePlugin import PngInfo
import base64,os,random
from io import BytesIO
import folder_paths
import node_helpers
import json,io
import comfy.utils
from comfy.cli_args import args
import cv2
import string,re
import math,glob
from .Watcher import FolderWatcher
from itertools import product
# 文件名排序
def sort_by_filename(items):
def extract_parts(filename):
# 使用正则表达式将文件名拆分为数字和非数字部分
parts = re.split(r'(\d+)', filename)
# 将数字部分转换为整数以便正确排序,同时保留非数字部分
parts = [int(part) if part.isdigit() else part for part in parts]
return parts
# 按照 file_name 的拆分部分进行排序
sorted_items = sorted(items, key=lambda x: extract_parts(x['file_name']))
return sorted_items
# 将PIL图片转换为OpenCV格式
def pil_to_opencv(image):
open_cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
return open_cv_image
# 将OpenCV格式图片转换为PIL格式
def opencv_to_pil(image):
pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
return pil_image
# 列出目录下面的所有文件
def get_files_with_extension(directory, extensions):
file_list = []
# 确保extensions参数是一个list,即使只有一个元素
if not isinstance(extensions, (tuple, list)):
extensions = [extensions]
for root, dirs, files in os.walk(directory):
# print(f"Files at {root}: {files}") # 确认files是一个字符串列表
for file in files:
# 检查文件是否以任何一个提供的扩展名结尾
if any(file.endswith(ext) for ext in extensions):
# 直接将文件名添加到列表中
file_list.append(file)
return file_list
def composite_images(foreground, background, mask, is_multiply_blend=False, position="overall", scale=0.25):
width, height = foreground.size
bg_image = background
bwidth, bheight = bg_image.size
scale = max(scale, 1 / bwidth)
scale = max(scale, 1 / bheight)
def determine_scale_option(width, height):
return 'height' if height > width else 'width'
if position == "overall":
layer = {
"x": 0,
"y": 0,
"width": bwidth,
"height": bheight,
"z_index": 88,
"scale_option": 'overall',
"image": foreground,
"mask": mask
}
else:
scale_option = determine_scale_option(width, height)
if scale_option == 'height':
scale = bheight * scale / height
else:
scale = bwidth * scale / width
new_width = int(width * scale)
new_height = int(height * scale)
if position == 'center_bottom':
x_position = int((bwidth - new_width) * 0.5)
y_position = bheight - new_height - 24
elif position == 'right_bottom':
x_position = bwidth - new_width - 24
y_position = bheight - new_height - 24
elif position == 'center_top':
x_position = int((bwidth - new_width) * 0.5)
y_position = 24
elif position == 'right_top':
x_position = bwidth - new_width - 24
y_position = 24
elif position == 'left_top':
x_position = 24
y_position = 24
elif position == 'left_bottom':
x_position = 24
y_position = bheight - new_height - 24
elif position == 'center_center':
x_position = int((bwidth - new_width) * 0.5)
y_position = int((bheight - new_height) * 0.5)
layer = {
"x": x_position,
"y": y_position,
"width": new_width,
"height": new_height,
"z_index": 88,
"scale_option": scale_option,
"image": foreground,
"mask": mask
}
# Resize the foreground image with antialiasing
try:
resampling_method = Image.Resampling.LANCZOS
except AttributeError:
resampling_method = Image.ANTIALIAS
layer_image = layer['image'].resize((layer['width'], layer['height']), resampling_method)
layer_mask = layer['mask'].resize((layer['width'], layer['height']), resampling_method)
bg_image.paste(layer_image, (layer['x'], layer['y']), layer_mask)
return bg_image.convert('RGB')
def count_files_in_directory(directory):
file_count = 0
for _, _, files in os.walk(directory):
file_count += len(files)
return file_count
def save_json_to_file(data, file_path):
with open(file_path, 'w') as file:
json.dump(data, file)
def draw_rectangle(image, grid, color,width):
x, y, w, h = grid
draw = ImageDraw.Draw(image)
draw.rectangle([(x, y), (x+w, y+h)], outline=color,width=width)
def generate_random_string(length):
letters = string.ascii_letters + string.digits
return ''.join(random.choice(letters) for _ in range(length))
def padding_rectangle(grid, padding):
x, y, w, h = grid
x -= padding
y -= padding
w += 2 * padding
h += 2 * padding
return (x, y, w, h)
class AnyType(str):
"""A special class that is always equal in not equal comparisons. Credit to pythongosssss"""
def __ne__(self, __value: object) -> bool:
return False
any_type = AnyType("*")
FONT_PATH= os.path.abspath(os.path.join(os.path.dirname(__file__),"..","assets","fonts"))
MAX_RESOLUTION=8192
# Tensor to PIL
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
# Convert PIL to Tensor
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
# 颜色迁移
# Color-Transfer-between-Images https://github.com/chia56028/Color-Transfer-between-Images/blob/master/color_transfer.py
def get_mean_and_std(x):
x_mean, x_std = cv2.meanStdDev(x)
x_mean = np.hstack(np.around(x_mean,2))
x_std = np.hstack(np.around(x_std,2))
return x_mean, x_std
def color_transfer(source,target):
# sources = ['s1','s2','s3','s4','s5','s6']
# targets = ['t1','t2','t3','t4','t5','t6']
# 将PIL的Image类型转换为OpenCV的numpy数组
source = cv2.cvtColor(np.array(source), cv2.COLOR_RGB2LAB)
target = cv2.cvtColor(np.array(target), cv2.COLOR_RGB2LAB)
s_mean, s_std = get_mean_and_std(source)
t_mean, t_std = get_mean_and_std(target)
height, width, channel = source.shape
for i in range(0,height):
for j in range(0,width):
for k in range(0,channel):
x = source[i,j,k]
x = ((x-s_mean[k])*(t_std[k]/s_std[k]))+t_mean[k]
# round or +0.5
x = round(x)
# boundary check
x = 0 if x<0 else x
x = 255 if x>255 else x
source[i,j,k] = x
source = cv2.cvtColor(source,cv2.COLOR_LAB2RGB)
# 创建PIL图像对象
image_pil = Image.fromarray(source)
return image_pil
# 组合
def create_big_image(image_folder, image_count):
# 计算行数和列数
rows = math.ceil(math.sqrt(image_count))
cols = math.ceil(image_count / rows)
# 获取每个小图的尺寸
small_width = 100
small_height = 100
# 计算大图的尺寸
big_width = small_width * cols
big_height = small_height * rows
# 创建一个新的大图
big_image = Image.new('RGB', (big_width, big_height))
# 获取所有图片文件的路径
image_files = [f for f in os.listdir(image_folder) if os.path.isfile(os.path.join(image_folder, f))]
# 遍历所有图片文件
for i, image_file in enumerate(image_files):
# 打开图片并调整大小
image = Image.open(os.path.join(image_folder, image_file))
image = image.resize((small_width, small_height))
# 计算当前小图的位置
row = i // cols
col = i % cols
x = col * small_width
y = row * small_height
# 将小图粘贴到大图上
big_image.paste(image, (x, y))
return big_image
# # 调用方法并保存大图
# image_folder = 'path/to/folder/containing/images'
# image_count = 100
# big_image = create_big_image(image_folder, image_count)
# big_image.save('path/to/save/big_image.jpg')
def naive_cutout(img, mask,invert=True):
"""
Perform a simple cutout operation on an image using a mask.
This function takes a PIL image `img` and a PIL image `mask` as input.
It uses the mask to create a new image where the pixels from `img` are
cut out based on the mask.
The function returns a PIL image representing the cutout of the original
image using the mask.
"""
# img=img.convert("RGBA")
mask=mask.convert("RGBA")
empty = Image.new("RGBA", (mask.size), 0)
red, green, blue, alpha = mask.split()
mask = mask.convert('L')
# 黑白,要可调
if invert==True:
mask = mask.point(lambda x: 255 if x > 128 else 0)
else:
mask = mask.point(lambda x: 255 if x < 128 else 0)
new_image = Image.merge('RGBA', (red, green, blue, mask))
cutout = Image.composite(img.convert("RGBA"), empty,new_image)
return cutout
# (h,w)
# (1072, 512) -- > [(536, 512),(536, 512)]
def split_mask_by_new_height(masks,new_height):
split_masks = torch.split(masks, new_height, dim=0)
return split_masks
def doMask(image,mask,save_image=False,filename_prefix="Mixlab",invert="yes",save_mask=False,prompt=None, extra_pnginfo=None):
output_dir = (
folder_paths.get_output_directory()
if save_image
else folder_paths.get_temp_directory()
)
(
full_output_folder,
filename,
counter,
subfolder,
_,
) = folder_paths.get_save_image_path(filename_prefix, output_dir)
image=tensor2pil(image)
mask = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3)
mask=tensor2pil(mask)
im=naive_cutout(image, mask,invert=='yes')
# format="image/png",
end="1" if invert=='yes' else ""
image_file = f"{filename}_{counter:05}_{end}.png"
mask_file = f"{filename}_{counter:05}_{end}_mask.png"
image_path=os.path.join(full_output_folder, image_file)
metadata = None
if not args.disable_metadata:
metadata = PngInfo()
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
im.save(image_path,pnginfo=metadata, compress_level=4)
result= [{
"filename": image_file,
"subfolder": subfolder,
"type": "output" if save_image else "temp"
}]
if save_mask:
mask_path=os.path.join(full_output_folder, mask_file)
mask.save(mask_path,
compress_level=4)
result.append({
"filename": mask_file,
"subfolder": subfolder,
"type": "output" if save_image else "temp"
})
return {
"result":result,
"image_path":image_path,
"im_tensor":pil2tensor(im.convert('RGB')),
"im_rgba_tensor":pil2tensor(im)
}
# 提取不透明部分
def get_not_transparent_area(image):
# 将PIL的Image类型转换为OpenCV的numpy数组
image_np = cv2.cvtColor(np.array(image), cv2.COLOR_RGBA2BGRA)
# 分离图像的RGBA通道
rgba = cv2.split(image_np)
alpha = rgba[3]
# 使用阈值将非透明部分转换为纯白色(255),透明部分转换为纯黑色(0)
_, mask = cv2.threshold(alpha, 1, 255, cv2.THRESH_BINARY)
# 获取非透明区域的边界框
coords = cv2.findNonZero(mask)
x, y, w, h = cv2.boundingRect(coords)
return (x, y, w, h)
def generate_gradient_image(width, height, start_color_hex, end_color_hex):
image = Image.new('RGBA', (width, height))
draw = ImageDraw.Draw(image)
if len(start_color_hex) == 7:
start_color_hex += "FF"
if len(end_color_hex) == 7:
end_color_hex += "FF"
start_color_hex = start_color_hex.lstrip("#")
end_color_hex = end_color_hex.lstrip("#")
# 将十六进制颜色代码转换为RGBA元组,包括透明度
start_color = tuple(int(start_color_hex[i:i+2], 16) for i in (0, 2, 4, 6))
end_color = tuple(int(end_color_hex[i:i+2], 16) for i in (0, 2, 4, 6))
for y in range(height):
# 计算当前行的颜色
r = int(start_color[0] + (end_color[0] - start_color[0]) * y / height)
g = int(start_color[1] + (end_color[1] - start_color[1]) * y / height)
b = int(start_color[2] + (end_color[2] - start_color[2]) * y / height)
a = int(start_color[3] + (end_color[3] - start_color[3]) * y / height)
# 绘制当前行的渐变色
draw.line((0, y, width, y), fill=(r, g, b, a))
# Create a mask from the image's alpha channel
mask = image.split()[-1]
# Convert the mask to a black and white image
mask = mask.convert('L')
image=image.convert('RGB')
return (image, mask)
# 示例用法
# width = 500
# height = 200
# start_color_hex = 'FF0000FF' # 红色,完全不透明
# end_color_hex = '0000FFFF' # 蓝色,完全不透明
# gradient_image = generate_gradient_image(width, height, start_color_hex, end_color_hex)
# gradient_image.save('gradient_image.png')
def rgb_to_hex(rgb):
r, g, b = rgb
hex_color = "#{:02x}{:02x}{:02x}".format(r, g, b)
return hex_color
# 读取不了分层
def load_psd(image):
layers=[]
print('load_psd',image.format)
if image.format=='PSD':
layers = [frame.copy() for frame in ImageSequence.Iterator(image)]
print('#PSD',len(layers))
else:
image = ImageOps.exif_transpose(image) #校对方向
layers.append(image)
return layers
def load_image(fp,white_bg=False):
im = Image.open(fp)
# ims=load_psd(im)
im = ImageOps.exif_transpose(im) #校对方向
ims=[im]
images=[]
for i in ims:
image = i.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if 'A' in i.getbands():
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
if white_bg==True:
nw = mask.unsqueeze(0).unsqueeze(-1).repeat(1, 1, 1, 3)
# 将mask的黑色部分对image进行白色处理
image[nw == 1] = 1.0
else:
mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
images.append({
"image":image,
"mask":mask
})
return images
# 读取图片数据,转成tensor
def load_image_to_tensor( image):
image_path = folder_paths.get_annotated_filepath(image)
img = node_helpers.pillow(Image.open, image_path)
output_images = []
output_masks = []
w, h = None, None
excluded_formats = ['MPO']
for i in ImageSequence.Iterator(img):
i = node_helpers.pillow(ImageOps.exif_transpose, i)
if i.mode == 'I':
i = i.point(lambda i: i * (1 / 255))
image = i.convert("RGB")
if len(output_images) == 0:
w = image.size[0]
h = image.size[1]
if image.size[0] != w or image.size[1] != h:
continue
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if 'A' in i.getbands():
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
else:
mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
output_images.append(image)
output_masks.append(mask.unsqueeze(0))
if len(output_images) > 1 and img.format not in excluded_formats:
output_image = torch.cat(output_images, dim=0)
output_mask = torch.cat(output_masks, dim=0)
else:
output_image = output_images[0]
output_mask = output_masks[0]
return (output_image, output_mask)
def load_image_and_mask_from_url(url, timeout=10):
# Load the image from the URL
response = requests.get(url, timeout=timeout)
content_type = response.headers.get('Content-Type')
image = Image.open(BytesIO(response.content))
# Create a mask from the image's alpha channel
mask = image.convert('RGBA').split()[-1]
# Convert the mask to a black and white image
mask = mask.convert('L')
image=image.convert('RGB')
return (image, mask)
# 获取图片s
def get_images_filepath(f,white_bg=False):
images = []
if os.path.isdir(f):
for root, dirs, files in os.walk(f):
for file in files:
file_path = os.path.join(root, file)
file_name=os.path.basename(file_path)
try:
imgs=load_image(file_path,white_bg)
for img in imgs:
images.append({
"image":img['image'],
"mask":img['mask'],
"file_path":file_path,
"file_name":file_name,
"psd":len(imgs)>1
})
except:
print('非图片',file_path)
elif os.path.isfile(f):
try:
file_path = os.path.join(root, f)
file_name=os.path.basename(file_path)
imgs=load_image(f,white_bg)
for img in imgs:
images.append({
"image":img['image'],
"mask":img['mask'],
"file_path":file_path,
"file_name":file_name,
"psd":len(imgs)>1
})
except:
print('非图片',f)
else:
print('路径不存在或无效',f)
return images
def get_average_color_image(image):
# 打开图片
# image = Image.open(image_path)
# 将图片转换为RGB模式
image = image.convert("RGB")
# 获取图片的像素值
pixel_data = image.load()
# 初始化颜色总和和像素数量
total_red = 0
total_green = 0
total_blue = 0
pixel_count = 0
# 遍历图片的每个像素
for i in range(image.width):
for j in range(image.height):
# 获取像素的RGB值
r, g, b = pixel_data[i, j]
# 累加颜色值
total_red += r
total_green += g
total_blue += b
# 像素数量加1
pixel_count += 1
# 计算平均颜色值
average_red = int(total_red // pixel_count)
average_green = int(total_green // pixel_count)
average_blue = int(total_blue // pixel_count)
# 返回平均颜色值
im = Image.new("RGB", (image.width, image.height), (average_red, average_green, average_blue))
hex=rgb_to_hex((average_red, average_green, average_blue))
return (im,hex)
# 创建噪声图像
def create_noisy_image(width, height, mode="RGB", noise_level=128, background_color="#FFFFFF"):
background_rgb = tuple(int(background_color[i:i+2], 16) for i in (1, 3, 5))
image = Image.new(mode, (width, height), background_rgb)
# 创建空白图像
# image = Image.new(mode, (width, height))
# 遍历每个像素,并随机设置像素值
pixels = image.load()
for i in range(width):
for j in range(height):
# 随机生成噪声值
noise_r = random.randint(-noise_level, noise_level)
noise_g = random.randint(-noise_level, noise_level)
noise_b = random.randint(-noise_level, noise_level)
# 像素值加上噪声值,并限制在0-255的范围内
r = max(0, min(pixels[i, j][0] + noise_r, 255))
g = max(0, min(pixels[i, j][1] + noise_g, 255))
b = max(0, min(pixels[i, j][2] + noise_b, 255))
# 设置像素值
pixels[i, j] = (r, g, b)
image=image.convert(mode)
return image
# 对轮廓进行平滑
def smooth_edges(alpha_channel, smoothness):
# 将图像中的不透明物体提取出来
# alpha_channel = image_rgba[:, :, 3]
# 0:表示设定的阈值,即像素值小于或等于这个阈值的像素将被设置为0。
# 255:表示设置的最大值,即像素值大于阈值的像素将被设置为255。
_, mask = cv2.threshold(alpha_channel, 127, 255, cv2.THRESH_BINARY)
# 对提取的不透明物体进行边缘检测
# edges = cv2.Canny(mask, 100, 200)
# 将一个整数变成最接近的奇数
smoothness = smoothness if smoothness % 2 != 0 else smoothness + 1
# 进行光滑处理
smoothed_mask = cv2.GaussianBlur(mask, (smoothness, smoothness), 0)
return smoothed_mask
def enhance_depth_map(depth_map, contrast):
# 打开深度图像
# depth_map = Image.open(im)
# 创建对比度增强对象
enhancer = ImageEnhance.Contrast(depth_map)
# 对深度图像进行对比度增强
enhanced_depth_map = enhancer.enhance(contrast)
return enhanced_depth_map
def detect_faces(image):
# Read the image
# image = cv2.imread('people1.jpg')
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGBA2BGRA)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Load the pre-trained face detector
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Detect faces in the image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=5, minSize=(50, 50))
# Create a black and white mask image
mask = np.zeros_like(gray)
# Loop over all detected faces
for (x, y, w, h) in faces:
# Draw rectangles around the detected faces
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Set the corresponding region in the mask image to white
mask[y:y+h, x:x+w] = 255
# Display the number of faces detected
print('Faces Detected:', len(faces))
mask = Image.fromarray(cv2.cvtColor(mask, cv2.COLOR_BGRA2RGBA))
return mask
def areaToMask(x,y,w,h,image):
# 创建一个与原图片大小相同的空白图片
mask = Image.new('L', image.size)
# 创建一个可用于绘制的对象
draw = ImageDraw.Draw(mask)
# 在空白图片上绘制一个矩形,表示要处理的区域
draw.rectangle((x, y, x+w, y+h), fill=255)
# 将处理区域之外的部分填充为黑色
draw.rectangle((0, 0, image.width, y), fill=0)
draw.rectangle((0, y+h, image.width, image.height), fill=0)
draw.rectangle((0, y, x, y+h), fill=0)
draw.rectangle((x+w, y, image.width, y+h), fill=0)
return mask
# def merge_images(bg_image, layer_image,mask, x, y, width, height):
# # 打开底图
# # bg_image = Image.open(background)
# bg_image=bg_image.convert("RGBA")
# # 打开图层
# layer_image=layer_image.convert("RGBA")
# layer_image = layer_image.resize((width, height))
# # mask = Image.new("L", layer_image.size, 255)
# mask = mask.resize((width, height))
# # 在底图上粘贴图层
# bg_image.paste(layer_image, (x, y), mask=mask)
# # 输出合成后的图片
# # bg_image.save("output.jpg")
# return bg_image
# ps的正片叠底
# 可以基于https://www.cnblogs.com/jsxyhelu/p/16947810.html ,用gpt写python代码
def multiply_blend(image1, image2):
image1=pil_to_opencv(image1)
image2=pil_to_opencv(image2)
# 将图像转换为浮点型
image1 = image1.astype(float)
image2 = image2.astype(float)
if image1.shape != image2.shape:
image1 = cv2.resize(image1, (image2.shape[1], image2.shape[0]))
# 归一化图像
image1 /= 255.0
image2 /= 255.0
# 正片叠底混合
blended = image1 * image2
# 将图像还原为8位无符号整数
blended = (blended * 255).astype(np.uint8)
blended=opencv_to_pil(blended)
return blended
# # 读取图像
# image1 = cv2.imread('1.png')
# image2 = cv2.imread('3.png')
# # 进行正片叠底混合
# result = multiply_blend(image1, image2)
# cv2.imwrite('result.jpg', result)
# 使用gpt4o优化代码
# 为了消除图像合并时出现的灰色描边,可以使用以下方法:
# 调整透明度:确保透明像素不会引入不需要的颜色。
# 预处理图像:在缩放图像之前,可以先将图像的边缘进行预处理,例如扩展边缘颜色,减少抗锯齿带来的过渡效果。
def merge_images(bg_image, layer_image, mask, x, y, width, height, scale_option, is_multiply_blend=False):
# 打开底图
bg_image = bg_image.convert("RGBA")
# 打开图层
layer_image = layer_image.convert("RGBA")
# 根据缩放选项调整图像大小
if scale_option == "height":
# 按照高度比例缩放
original_width, original_height = layer_image.size
scale = height / original_height
new_width = int(original_width * scale)
layer_image = layer_image.resize((new_width, height), Image.NEAREST)
elif scale_option == "width":
# 按照宽度比例缩放
original_width, original_height = layer_image.size
scale = width / original_width
new_height = int(original_height * scale)
layer_image = layer_image.resize((width, new_height), Image.NEAREST)
elif scale_option == "overall":
# 整体缩放
layer_image = layer_image.resize((width, height), Image.NEAREST)
elif scale_option == "longest":
original_width, original_height = layer_image.size
if original_width > original_height:
new_width = width
scale = width / original_width
new_height = int(original_height * scale)
x = 0
y = int((height - new_height) * 0.5)
else:
new_height = height
scale = height / original_height
new_width = int(original_height * scale)
x = int((width - new_width) * 0.5)
y = 0
# 调整mask的大小
nw, nh = layer_image.size
mask = mask.resize((nw, nh), Image.NEAREST)
# 预处理图像边缘以减少灰色描边
layer_image = layer_image.filter(ImageFilter.SMOOTH)
if is_multiply_blend:
bg_image_white = Image.new("RGB", bg_image.size, (255, 255, 255))
bg_image_white.paste(layer_image, (x, y), mask=mask)
bg_image = multiply_blend(bg_image_white, bg_image)
bg_image = bg_image.convert("RGBA")
else:
transparent_img = Image.new("RGBA", layer_image.size, (255, 255, 255, 0))
# 调整透明度处理
for i in range(transparent_img.size[0]):
for j in range(transparent_img.size[1]):
r, g, b, a = transparent_img.getpixel((i, j))
if a > 0:
transparent_img.putpixel((i, j), (r, g, b, 255))
transparent_img.paste(layer_image, (0, 0), mask)
bg_image.paste(transparent_img, (x, y), transparent_img)
# 输出合成后的图片
return bg_image
#MixCopilot
def resize_2(img):
# 检查图像的高度是否是2的倍数,如果不是,则调整高度
if img.height % 2 != 0:
img = img.resize((img.width, img.height + 1))
# 检查图像的宽度是否是2的倍数,如果不是,则调整宽度
if img.width % 2 != 0:
img = img.resize((img.width + 1, img.height))
return img
# TODO 几个像素点的底
def resize_image(layer_image, scale_option, width, height,color="white"):
layer_image = layer_image.convert("RGB")
original_width, original_height = layer_image.size
if scale_option == "height":
# Scale image based on height
scale = height / original_height
new_width = int(original_width * scale)
layer_image = layer_image.resize((new_width, height))
elif scale_option == "width":
# Scale image based on width
scale = width / original_width
new_height = int(original_height * scale)
layer_image = layer_image.resize((width, new_height))
elif scale_option == "overall":
# Scale image overall
layer_image = layer_image.resize((width, height))
elif scale_option == "center":
# Scale image to minimum of width and height, center it, and fill extra area with black
scale = min(width / original_width, height / original_height)
new_width = math.ceil(original_width * scale)
new_height = math.ceil(original_height * scale)
resized_image = Image.new("RGB", (width, height), color=color)
resized_image.paste(layer_image.resize((new_width, new_height)), ((width - new_width) // 2, (height - new_height) // 2))
resized_image = resized_image.convert("RGB")
resized_image=resize_2(resized_image)
return resized_image
elif scale_option == "longest":
#暂时不用,
if original_width > original_height:
new_width=width
scale = width / original_width
new_height = int(original_height * scale)
x=0
y=int((new_height-height)*0.5)
resized_image = Image.new("RGB", (new_width, new_height), color=color)
resized_image.paste(layer_image.resize((new_width, new_height)), (x,y))
resized_image = resized_image.convert("RGB")
resized_image=resize_2(resized_image)
return resized_image
else:
new_height=height
scale = height / original_height
new_width = int(original_height * scale)
x=int((new_width-width)*0.5)
y=0
resized_image = Image.new("RGB", (new_width, new_height), color=color)
resized_image.paste(layer_image.resize((new_width, new_height)), (x,y))
resized_image = resized_image.convert("RGB")
resized_image=resize_2(resized_image)
return resized_image
layer_image=resize_2(layer_image)
return layer_image
def generate_text_image(text,
font_path,
font_size,
text_color,
vertical=True,
stroke=False,
stroke_color=(0, 0, 0),
stroke_width=1,
spacing=0,
line_spacing=0,
padding=4,
max_characters_per_line=48,
fixed_width=None):
def split_text(text, max_chars, fixed_width=False):
lines = []
current_line = ""
current_length = 0
for char in text:
if char == '\n':
lines.append(current_line)
current_line = ""
current_length = 0
elif '\u4e00' <= char <= '\u9fff': # Chinese character
if current_length + 1 <= max_chars:
current_line += char
current_length += 1
else:
lines.append(current_line)