我有這個功能,我想將其應用于影像檔案并將它們中的每一個保存在一個單獨的檔案中:
import argparse
import numpy as np
from PIL import Image
def MyFn(img, saveFile=None, Io=240, alpha=1, beta=0.15):
HERef = np.array([[0.5626, 0.2159],
[0.7201, 0.8012],
[0.4062, 0.5581]])
maxCRef = np.array([1.9705, 1.0308])
h, w = img.shape[:2]
img = img.reshape((-1,3))
OD = -np.log((img.astype(np.float) 1)/Io)
ODhat = OD[~np.any(OD<beta, axis=1)]
eigvals, eigvecs = np.linalg.eigh(np.cov(ODhat.T))
That = ODhat.dot(eigvecs[:,1:3])
phi = np.arctan2(That[:,1],That[:,0])
minPhi = np.percentile(phi, alpha)
maxPhi = np.percentile(phi, 100-alpha)
vMin = eigvecs[:,1:3].dot(np.array([(np.cos(minPhi), np.sin(minPhi))]).T)
vMax = eigvecs[:,1:3].dot(np.array([(np.cos(maxPhi), np.sin(maxPhi))]).T)
if vMin[0] > vMax[0]:
HE = np.array((vMin[:,0], vMax[:,0])).T
else:
HE = np.array((vMax[:,0], vMin[:,0])).T
Y = np.reshape(OD, (-1, 3)).T
C = np.linalg.lstsq(HE,Y, rcond=None)[0]
maxC = np.array([np.percentile(C[0,:], 99), np.percentile(C[1,:],99)])
tmp = np.divide(maxC,maxCRef)
C2 = np.divide(C,tmp[:, np.newaxis])
Inorm = np.multiply(Io, np.exp(-HERef.dot(C2)))
Inorm[Inorm>255] = 254
Inorm = np.reshape(Inorm.T, (h, w, 3)).astype(np.uint8)
H = np.multiply(Io, np.exp(np.expand_dims(-HERef[:,0], axis=1).dot(np.expand_dims(C2[0,:], axis=0))))
H[H>255] = 254
H = np.reshape(H.T, (h, w, 3)).astype(np.uint8)
E = np.multiply(Io, np.exp(np.expand_dims(-HERef[:,1], axis=1).dot(np.expand_dims(C2[1,:], axis=0))))
E[E>255] = 254
E = np.reshape(E.T, (h, w, 3)).astype(np.uint8)
if saveFile is not None:
Image.fromarray(Inorm).save(saveFile '.png')
Image.fromarray(H).save(saveFile '_H.png')
Image.fromarray(E).save(saveFile '_E.png')
return Inorm, H, E
對一張影像進行測驗,它成功運行:
img = np.array(Image.open('/Desktop/Dataset/Images/img1.png'))
output = 'Desktop/Dataset/Output'
MyFn(img = img,saveFile = output) #Apply this function which saves in output file
但是,如何將此代碼應用于檔案夾中的所有影像?代碼運行但只保存一張影像。
import glob
images = glob.glob('/Desktop/Dataset/Images/*')
for img in images:
img = np.array(Image.open(img))
output = 'Desktop/Dataset/Output'
MyFn(img = img,saveFile = output)
uj5u.com熱心網友回復:
您沒有sv在第二個代碼段中定義值。
由于影像將被覆寫,請嘗試以下代碼:
import glob
images = glob.glob('/Desktop/Dataset/Images/*')
i = 0
for img in images:
i = 1 #iteration to avoid overwrite
img = np.array(Image.open(img))
output = 'Desktop/Dataset/Output'
MyFn(img = img str(i),saveFile = output)
uj5u.com熱心網友回復:
嘗試直接使用庫 os
import os
entries = os.listdir('image/')
這會將所有檔案的串列回傳到您的檔案夾中
uj5u.com熱心網友回復:
這是因為您沒有sv在回圈中設定值。您應該在每次迭代時將其設定為不同的值,以便將其寫入不同的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/424718.html
上一篇:基于查找表有效替換多列中的字串
下一篇:創建遍歷兩個串列的新串列
