import PIL.Image as Image # 以第一个像素为准,相同色改为透明 def transparent_back(img): img = img.convert('RGBA') L, H = img.size color_0 = img.getpixel((0,0)) for h in range(H): for l in range(L): dot = (l,h) color_1 = img.getpixel(dot) if color_1 == color_0: color_1 = color_1[:-1] + (0,) img.putpixel(dot,color_1) return img if __name__ == '__main__': img=Image.open(r'I:\18Breakageratecalculation\SVM run\1\segment_1.png') img=transparent_back(img) img.save(r'I:\18Breakageratecalculation\SVM run\1\segment_12.png')批量将图片转化为透明图片
时间: 2024-03-11 10:51:33 浏览: 116
批量将png图片背景色改为透明
你的问题是如何批量将图片转化为透明图片。你可以使用以下代码实现:
```
import os
import PIL.Image as Image
def transparent_back(img):
img = img.convert('RGBA')
L, H = img.size
color_0 = img.getpixel((0,0))
for h in range(H):
for l in range(L):
dot = (l,h)
color_1 = img.getpixel(dot)
if color_1 == color_0:
color_1 = color_1[:-1] + (0,)
img.putpixel(dot,color_1)
return img
if __name__ == '__main__':
input_path = r'I:\18Breakageratecalculation\SVM run\1'
output_path = r'I:\18Breakageratecalculation\SVM run\1_transparent'
if not os.path.exists(output_path):
os.makedirs(output_path)
for file_name in os.listdir(input_path):
if file_name.endswith('.png'):
img_path = os.path.join(input_path, file_name)
img = Image.open(img_path)
img = transparent_back(img)
output_img_path = os.path.join(output_path, file_name)
img.save(output_img_path)
```
这段代码的作用是将指定文件夹下的所有 PNG 格式的图片转化为透明图片,并保存到新的文件夹中。你只需要将 input_path 和 output_path 改为你自己的路径即可。
阅读全文