我正在嘗試使用 OpenCV 將我訓練的模型的結果轉換為 png 影像。我的輸出有 4 個通道,我不確定如何將這 4 個通道轉換為 png。
# Load the model
model = CNNSEG()
model.load_state_dict(torch.load(PATH))
model.eval()
for iteration, sample in enumerate(test_data_loader):
img = sample
print(img.shape)
plt.imshow(img[0,...].squeeze(), cmap='gray') #visualise all images in test set
plt.pause(1)
# output the results
img_in = img.unsqueeze(1)
output = model(img_in) # shape: [2, 4, 96, 96]
如這里所示,輸出的形狀是 [2, 4, 96, 96],它們是批量大小、通道、高度和寬度。那么我該怎么做才能將其轉換為 png 影像呢?
uj5u.com熱心網友回復:
要撰寫影像,您需要將輸出轉換為正確的格式(假設輸出在 0,1 范圍內):
# Convert outputs from 0-1 to 0, 255
img_in *= 255.0
# Convert floats to bytes
img_in = img_in.astype(np.uint8)
# Transpose the images from channel first (4, 96, 96) to channel last (96, 96, 4)
image1 = img_in[0, :, :, :].transpose(2, 1, 0)
image2 = img_in[1, :, :, :].transpose(2, 1, 0)
然后只是保存影像的問題:
cv2.imwrite('./example_path/image1.png', image1)
cv2.imwrite('./example_path/image2.png', image2)
uj5u.com熱心網友回復:
您可能希望將影像基本上分成兩個,然后單獨保存它們。
import numpy as np
import cv2
img = np.ones((2,4,96,96),dtype=np.uint8) #creating a random image
img1 = img[0,:,:,:] #extracting the two separate images
img2 = img[1,:,:,:]
img1_reshaped = img1.transpose() #reshaping them to the desired form of (w,h,c)
img2_reshaped = img2.transpose()
cv2.imwrite("img1.png",img1_reshaped) #save the images as .png
cv2.imwrite("img2.png",img2_reshaped)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363193.html
標籤:Python opencv 火炬 卷积神经网络 图像分割
上一篇:Tensorflow:ValueError:Input0isincompatiblewithlayermodel:expectedshape=(None,99),foundshape=(None,3)
下一篇:AttributeError:模塊'cv2.cv2'沒有屬性'SURF_create',2.模塊'cv2.cv2'沒有屬性'xfe
