1 回答

TA貢獻1776條經驗 獲得超12個贊
您正在將圖像轉換為 PyTorch 張量,并且在 PyTorch 中圖像的大小為[C, H, W]。當您將它們可視化時,您正在將張量轉換回 NumPy 數組,其中圖像的大小為[H, W, C]。因此,您正在嘗試重新排列維度,但您使用的是torch.reshape
,它不會交換維度,而只會以不同的方式對數據進行分區。
一個例子使這一點更清楚:
# Incrementing numbers with size 2 x 3 x 3
image = torch.arange(2 * 3 * 3).reshape(2, 3, 3)
# => tensor([[[ 0, 1, 2],
# [ 3, 4, 5],
# [ 6, 7, 8]],
#
# [[ 9, 10, 11],
# [12, 13, 14],
# [15, 16, 17]]])
# Reshape keeps the same order of elements but for a different size
# The numbers are still incrementing from left to right
image.reshape(3, 3, 2)
# => tensor([[[ 0, 1],
# [ 2, 3],
# [ 4, 5]],
#
# [[ 6, 7],
# [ 8, 9],
# [10, 11]],
#
# [[12, 13],
# [14, 15],
# [16, 17]]])
要重新排序您可以使用的尺寸permute:
# Dimensions are swapped
# Now the numbers increment from top to bottom
image.permute(1, 2, 0)
# => tensor([[[ 0, 9],
# [ 1, 10],
# [ 2, 11]],
#
# [[ 3, 12],
# [ 4, 13],
# [ 5, 14]],
#
# [[ 6, 15],
# [ 7, 16],
# [ 8, 17]]])
使用 時.astype(np.uint8),組織圖像完全是黑色的。
PyTorch 圖像表示為值介于 [0, 1] 之間的浮點數,但 NumPy 使用介于 [0, 255] 之間的整數值。將浮點值轉換為np.uint8將導致只有 0 和 1,其中不等于 1 的所有內容都將設置為 0,因此整個圖像為黑色。
您需要將這些值乘以 255 以將它們置于 [0, 255] 范圍內。
img = img.permute(1, 2, 0) * 255
img = img.numpy().astype(np.uint8)
當您將張量轉換為 PIL 圖像時,此轉換也會自動完成transforms.ToPILImage(或者TF.to_pil_image如果您更喜歡函數式版本,則使用)并且 PIL 圖像可以直接轉換為 NumPy 數組。這樣您就不必擔心尺寸、值范圍或類型,上面的代碼可以替換為:
img = np.array(TF.to_pil_image(img))
添加回答
舉報