You need to enable JavaScript to run this app. 如何将深度学习模型测试得到的预测结果转换为PNG格式图片
优惠活动
大模型
产品
解决方案
定价
更多

如何将深度学习模型测试得到的预测结果转换为PNG格式图片

修正方案

你原有代码无法正常保存PNG格式掩码的核心原因有3个:

  • 模型输出的pred是形状为(1, 图像高度, 图像宽度, 1)的浮点数组,取值范围为0~1的概率值,不能直接传入Image.fromarray生成有效图像
  • 保存前没有做二值化处理(你可视化时用到的>0.5阈值逻辑没有加到保存流程里)
  • 保存路径拼接错误,多了多余的单引号,且循环内手动给i自增属于冗余逻辑,for循环已经自动迭代i值

你可以直接替换原有循环的保存部分代码,修改后的完整循环逻辑如下:

from PIL import Image
import numpy as np
import cv2
import matplotlib.pyplot as plt

for i in range(30):
    index = np.random.randint(1, len(df2.index))
    # 读取并预处理原图
    img = cv2.imread(df2['filename'].iloc[index])
    img = cv2.resize(img, (im_height, im_width))
    img = img / 255
    img = img[np.newaxis, :, :, :]
    # 模型预测
    pred = model.predict(img)  

    # 可视化部分(保留原有逻辑)
    plt.figure(figsize=(12,12))
    plt.subplot(1,3,1)
    plt.imshow(np.squeeze(img))
    plt.title('Original Image')
    plt.subplot(1,3,2)
    plt.imshow(np.squeeze(cv2.imread(df2['mask'].iloc[index])))
    plt.title('Original Mask')
    plt.subplot(1,3,3)
    plt.imshow(np.squeeze(pred) > .5)
    plt.title('Prediction')
    plt.show()  

    # ========== 修正后的保存逻辑 ==========
    # 1. 去掉多余维度,二值化处理
    pred_mask = (np.squeeze(pred) > 0.5).astype(np.uint8)
    # 2. 将二值的0/1转为0/255,适配PNG图像存储规范
    pred_mask *= 255
    # 3. 生成PIL图像并保存,修正路径拼接逻辑
    im = Image.fromarray(pred_mask)
    save_path = r'C:\Users\Admin\Desktop\saglika2\Test\predicted_maske\{}_pred_image.png'.format(i)
    im.save(save_path)

如果需要保存带伪彩色的预测结果(和可视化展示的效果完全一致),可以替换保存逻辑为:

# 保存伪彩色预测掩码
plt.imshow(np.squeeze(pred) > .5)
plt.axis('off') # 去掉坐标轴
plt.savefig(r'C:\Users\Admin\Desktop\saglika2\Test\predicted_maske\{}_pred_color.png'.format(i), 
            bbox_inches='tight', pad_inches=0)
plt.close()

内容的提问来源于stack exchange,提问作者Serdar ASARKAYA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 11:54:04