【问题标题】:How to save png images with OpenCV如何使用 OpenCV 保存 png 图像
【发布时间】:2021-12-27 23:18:34
【问题描述】:

我正在尝试使用 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 图像呢?

【问题讨论】:

  • 只做imwrite,有什么问题?你调查过这个吗?
  • @Mahrkeenerh,再看看形状。不适合 imwrite()
  • @berak 您可以遍历数组并一一写入。再次,有什么问题?还是您的意思是 rgba 是第一个维度?

标签: python opencv pytorch conv-neural-network image-segmentation


【解决方案1】:

要编写图像,您需要将输出转换为正确的格式(假设输出在 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)

【讨论】:

    【解决方案2】:

    您可能希望将图像分成两部分,然后分别保存。

    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)
    

    【讨论】:

    • 重塑不起作用。你没有尝试过这个
    • @berak 我确实在整形后保存了图像。
    • @berak 同意你的看法。重塑将不起作用。检查了这个例子 --> mxnet.apache.org/versions/1.5.0/tutorials/basic/… 感谢您指出。更新答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 2011-01-19
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2012-09-21
    相关资源
    最近更新 更多