我需要将从多个文件夹中的多个图像派生的像素强度列表导出到Excel电子表格。每个文件夹都包含一个tiff文件列表,每个文件代表一个游戏中时光倒流的特定时间点。我已经设法获得每个文件夹子集的像素强度,但我正在努力使用带有pandas的DataFrames来优化输出。数据框仅显示最后一个文件夹中的值列表,我需要电子表格在单独的行中显示每个列表。这就是我所拥有的:
import os
import matplotlib.pyplot as plt
import skimage.external.tifffile as tiff
import pandas as pd
from pandas import DataFrame
#to read images in each folder
def load_images_from_folder(folder):
images=[]
for filename in os.listdir(folder):
if any([filename.endswith(x) for x in ['.tif']]):
img=tiff.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
return images
folders = [
'path to folder1',
'path to folder2',
'path to folder3',
]
for folder in folders:
images=load_images_from_folder(folder)
#ratio the mean green to red signal in each image
ratios = [image[..., 1].mean() / image[..., 0].mean() for image in
images]
plt.plot(range(len(images)), ratios)
plt.show()
df=DataFrame({'Ratios':ratios})
df.to_excel('Ratios.xlsx', sheet_name='sheet1', index=0)
打印出比率给出: 文件夹1: [值列表] 文件夹2: [值列表] Folder3: [值列表 等等 但是df(DataFrame)显示的数据仅来自Folder3中的列表。那么,我需要做些什么来将从多个文件夹派生的值导出到Excel中呢?我还确保每个图像都作为ndarray读取,type = uint8。
答案 0 :(得分:0)
通过调用extend
列表方法替换for循环中的赋值语句应该可以解决问题:
images = []
for folder in folders:
images.extend(load_images_from_folder(folder))
答案 1 :(得分:0)
import tkinter
from tkinter import filedialog
from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askdirectory
import os
import matplotlib.pyplot as plt
import skimage.external.tifffile as tiff
import pandas as pd
from pandas import DataFrame
import numpy as np
def load_images_from_folder(folder):
images=[]
for filename in os.listdir(folder):
if any([filename.endswith(x) for x in ['.tif']]):
img=tiff.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
return images
tkinter.Tk().withdraw()
dirname = askdirectory(initialdir="/", title='Please select a directory')
os.chdir(dirname)
data = pd.DataFrame([])
ratiodata = []
foldernames = []
for folder in os.listdir(dirname):
if not folder.endswith('.xlsx'):
images=load_images_from_folder(folder)
green=[image[..., 1].mean() for image in images]
red=[image[..., 0].mean() for image in images]
ratios= [img[..., 1].mean() / img[..., 0].mean() for img in images]
#PLOTS
temp = pd.DataFrame({folder + " ratios" : ratios})
data = pd.concat([data,temp],axis=1)
data.to_excel('test.xlsx', sheet_name='sheet1')