![](/img/trans.png)
[英]How to save (write) a list of images from a dataset into a new folder - openCV Python?
[英]new in python. I want to apply an algorithm to different images from a folder and save the new ones in another folder. Biology research images
我想在黑白图像中反转颜色,然后使用以下代码更改透明背景:
imgg = Image.open('HSPl4_E5_LP8.png')
data = np.array(imgg)
converted = np.where(data == 255, 0, 255)
imgg = Image.fromarray(converted.astype('uint8'))
imgg.save('new HSPl4_E5_LP8.png')
和
from PIL import Image
img = Image.open('new HSPl4_E5_LP8.png')
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))#0 és la alfa de rgba i significa 0 opacity.
else:
newData.append(item)
img.putdata(newData)
img.save("HSPl4_E5_LP8 transparent.png", "PNG")
然后我想在文件夹中的多个图像中迭代它。 然后我想将更改后的新图像保存在另一个文件夹中。 但我没有找到让它工作的方法。
不确定我是否正确理解您的问题,但我认为您可以执行以下操作。 首先,您将两个操作捆绑到一个函数中:
from PIL import Image
def imageTransform(imgfile,destfolder):
img = Image.open(imgfile)
data = np.array(img)
converted = np.where(data == 255, 0, 255)
img = Image.fromarray(converted.astype('uint8'))
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save(destfolder+"/"+imgfile, "PNG")
此功能将打开一个图像,应用您提到的更改,然后将其保存在指定路径中。 然后,您可以使用以下代码自动执行此过程:
import os
originalfolder = "folderpath" #place your folder path as string
destfolder = "folderpath" #place your destination path as string
directory = os.fsencode(originalfolder)
for file in os.listdir(directory):
filename = os.fsdecode(file)
imageTransform(file, destfolder)
“原始文件夹”是原始图像所在的文件夹。 格式应该类似于"C:/Users/yourfolder"
“desfolder”是存储新图像的文件夹。 格式应该类似于"C:/Users/yournewfolder"
您可以为此使用 pathlib,假设 apply_algo 是一个函数,它接受输入图像的路径对象并返回转换后的 PIL.Image 对象,这应该可以工作。
from pathlib import Path
def process_files(source: str, dstn: str):
dstn = Path(dstn)
source = Path(source)
# check if input strings are directories or not.
if not (source.is_dir() and dstn.is_dir()):
raise Exception("Source and Dstn must be directories")
# use rglob if you want to pick files from subdirectories as well
for path in source.glob("*"):
if path.is_file():
output_img = apply_algo(path)
output_img.save(dstn / path.name(), "PNG")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.