首页 > 其他分享 >合并两个文件夹下名称交集的标签

合并两个文件夹下名称交集的标签

时间:2023-05-19 10:12:22浏览次数:31  
标签:交集 标签 list 文件夹 common file new path os

标签为黑白图,合并两个文件夹下名称交集的标签

 

 1 # 合并两个文件夹下相同名称的两张png标签
 2 #
 3 # 开发时间:2023/5/18 16:38
 4 import os
 5 
 6 from PIL import Image
 7 
 8 def merge(path1, path2, path3):
 9     # 打开第一张图片
10     img1 = Image.open(path1)
11     # 打开第二张图片
12     img2 = Image.open(path2)
13     # 获取图片的大小
14     width, height = img1.size
15     # 创建新的图片对象
16     new_img = Image.new('L', (width, height), 0)
17     # 合并两张图片
18     for x in range(width):
19         for y in range(height):
20             pixel1 = img1.getpixel((x, y))
21             pixel2 = img2.getpixel((x, y))
22             if pixel1 == 255 or pixel2 == 255:
23                 new_img.putpixel((x, y), 255)
24             else:
25                 new_img.putpixel((x, y), 0)
26 
27     file_name = os.path.split(path1)[1]
28 
29     path_new = os.path.join(path3, file_name)
30     # 保存新的图片
31     new_img.save(path_new)
32 
33 
34 # 提取需要合并的同名文件
35 A_file_path = 'Ajson'
36 A_fileList = os.listdir(A_file_path)
37 
38 B_file_path = 'Bjson'
39 B_fileList = os.listdir(B_file_path)
40 
41 Alist = []
42 for file_a in A_fileList:
43     Alist.append(file_a)
44 
45 Blist = []
46 for file_b in B_fileList:
47     Blist.append(file_b)
48 
49 # 将列表转化为集合,并计算交集
50 common_set = set(Alist).intersection(set(Blist))
51 
52 # 将交集转换为列表
53 common_list = list(common_set)
54 
55 if len(common_list) == 0:
56     print("这两个列表没有相同的元素")
57 else:
58     print("这两个列表有相同的元素:")
59     print(len(common_list))
60 
61     for item in common_list:
62         print(item)
63     print(len(common_list))
64 
65 
66 # 拼接目录,遍历合并
67 for item in common_list:
68 
69     path_a = os.path.join(A_file_path, item)
70     path_b = os.path.join(B_file_path, item)
71     path_result = 'result'
72     if not os.path.exists(path_result):
73         os.makedirs(path_result)
74 
75     merge(path_a, path_b, path_result)

 

标签:交集,标签,list,文件夹,common,file,new,path,os
From: https://www.cnblogs.com/yokon/p/17414105.html

相关文章