我有存盤在 pandas 資料框中的 16 個 32x32px 影像的灰度影像資料。每個資料行代表一個影像的序列化像素資料,因此資料幀有 1024 列。
我想重塑資料以不僅恢復原始影像大小,而且將所有重塑后的影像串聯(水平)。
所以第一行看起來像這樣:前 32 列:影像 1 - 第一行像素,第二 32 列:影像 2 - 第一行像素,...
第二行將如下所示:前 32 列:影像 1 - 第二行像素,第二 32 列:影像 2 - 第二行像素,...
所以基本上,我想將我的資料框從 (32 * 32) x 16 重塑為 (32 * 16) x 32。我想使用這些資料在之后使用 PIL 創建影像。
有沒有一種優雅的方式來做到這一點?我現在有點迷失了,因為我對完全使用 pandas 和 Python 還是很陌生。我不期待一個完整的答案,但如果你至少能把我推向正確的方向,那就太好了。
uj5u.com熱心網友回復:
這里有三個不同的功能,第一個使用 Pandas 方法(堆疊)。第二個使用常規 python 串列,逐行構建結果。最后一個使用 numpy 重塑。
numpy 重塑方法的效率是其他方法的兩倍,幾乎所有計算時間實際上都花在將 DataFrame 轉換為 numpy 陣列格式,然后再轉換回 pandas 上。
如果您想使用代碼,這里是我用于此的筆記本的鏈接。
def stack_image_df(image_df):
"""
Performance: 100 loops, best of 5: 19 ms per loop
"""
# create a MultiIndex indicating Row and Column information for each image
row_col_index = pd.MultiIndex.from_tuples(
[(i // 32, i % 32) for i in range(0, 1024)], name=["row", "col"]
)
image_df.columns = row_col_index
image_df.index = range(1, 17)
image_df.index.name = "Image"
# Use MultiIndex to reshape data
return image_df.stack(level=1).T
def build_image_df(image_df):
"""
Performance: 10 loops, best of 5: 19.2 ms per loop
"""
image_data = image_df.values.tolist()
reshaped = []
for r_num in range(0, 32):
row = []
for image_num in range(0, 16):
# for each image
for c_num in range(0, 32):
# get the corresponding index in the raw data
# and add the pixel data to the row we're building
raw_index = r_num * 32 c_num
pixel = image_data[image_num][raw_index]
row.append(pixel)
reshaped.append(row)
reshaped_df = pd.DataFrame(reshaped)
return reshaped_df
def reshape_image_df(image_df):
"""
Performance: 100 loops, best of 5: 9.56 ms per loop
Note: numpy methods only account for 0.82 ms of this
"""
return pd.DataFrame(
image_df.to_numpy().reshape(512, 32).transpose()
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453077.html
上一篇:向量化2D陣列和每行另一個2D陣列之間的NumPY點積
下一篇:使用Flex問題定位多個Div
