簡體   English   中英

新的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM