图像分割:将分割结果可视化(批量处理)

语义分割的输出结果往往没有叠加在原图像上,因此很难直观看出训练结果的好坏,因此考虑将分割结果叠加在原图上,这样就能直观看出分割的细节。

代码:

# demo.py
import os
import cv2
import numpy as np


def overlay_and_save(original_folder, segmentation_folder, output_folder):
    # Gets the list in the original image folder
    original_files = os.listdir(original_folder)

    # check output folder
    output_path = os.path.join(segmentation_folder, output_folder)
    os.makedirs(output_path, exist_ok=True)

    for original_file in original_files:
        original_path = os.path.join(original_folder, original_file)
        segmentation_path = os.path.join(segmentation_folder, os.path.splitext(original_file)[0] + ".png")

        original_img = cv2.imread(original_path)
        segmentation_result = cv2.imread(segmentation_path)

        # check
        if original_img is None or segmentation_result is None:
            print(f"Failed to read {original_file}. Skipping...")
            continue

        overlay_result = plot_segmentation(original_img, segmentation_result)

        output_file_path = os.path.join(output_path, f"{original_file}_overlay")
        cv2.imwrite(output_file_path, overlay_result)
    print("Done!")


def plot_segmentation(img, segmentation_result, colors=None, alpha=0.5) -> np.ndarray:
    """
    Visualize segmentation results.

    Parameters:
    - img: numpy.ndarray
        Original image with shape `(H, W, 3)`.
    - segmentation_result: numpy.ndarray
        Segmentation result with shape `(H, W, C)`, where `C` is the number of classes.
    - colors: numpy.ndarray
        Colors for each class, shape `(C, 3)`.
        If None, generate random colors for each class.
    - alpha: float, optional, default 0.5
        Transparency of the plotted segmentation result.

    Returns:
    - numpy.ndarray
        Image plotted with segmentation colors, shape `(H, W, 3)`.
    """
    if colors is None:
        # colors = np.random.random((segmentation_result.shape[0], 3)) * 255
        colors = np.array([
            [0, 0, 0],  # _background_
            [0, 255, 255],  # lane
        ])
    else:
        if colors.shape != (2, 3):
            # if colors.shape[0] < segmentation_result.shape[-1]:
            raise RuntimeError(
                f"colors count: {colors.shape[0]} is less than classes count: {segmentation_result.shape[-1]}"
            )
    # print(segmentation_result.shape)

    for class_idx in range(2):
        # for class_idx in range(segmentation_result.shape[-1]):
        class_mask = segmentation_result[:, :, class_idx]
        color = colors[class_idx]

        img = np.where(np.stack([class_mask] * 3, axis=-1), img * (1 - alpha) + color * alpha, img)

    return img.astype(np.uint8)


original_folder = "your_original_image_path/"
segmentation_folder = "your_segmentation_image_path/"
output_folder = "Plot"
overlay_and_save(original_folder, segmentation_folder, output_folder)

参考:

 https://butui.me/posts/plot-mask-on-image/

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,我可以为您提供用PyTorch实现UNet图像分割的一般步骤。下面是一个简单的示例: 步骤1:数据准备 - 收集和准备需要分割图像和相应的标签。图像和标签应该是成对的,标签必须与图像大小相同。 - 将数据集拆分为训练集和验证集。可以使用PyTorch的Dataset和DataLoader类来加载和预处理数据。 步骤2:定义UNet模型 - 定义UNet模型的架构,包括编码器和解码器。 - 编写前向传递函数,其中包括将输入图像传递给编码器、从编码器中获取特征图、将特征图传递给解码器、将解码器的输出与相应的编码器输出级联起来生成最终的分割结果。 步骤3:定义损失函数 - 选择一个适合任务的损失函数。在图像分割中,常见的损失函数包括二进制交叉熵、Dice系数等。 - 编写损失函数计算代码。 步骤4:定义优器 - 选择一个适合任务的优器,常用的有Adam、SGD等。 - 设置优器的超参数,如学习率、动量等。 步骤5:训练模型 - 编写训练代码,并设置超参数,如批量大小、训练轮数等。 - 在每个epoch中,循环遍历训练集并计算损失。 - 使用优器反向传播并更新权重。 步骤6:评估模型 - 编写评估代码,计算模型在验证集上的准确率、精度、召回率等指标。 - 通过可实际预测结果,检查模型是否能够准确地将图像分割为正确的类别。 步骤7:测试模型 - 在测试集上运行模型,计算模型的预测性能。 - 对模型输出的分割结果进行后处理,如去除孤立点、填充空洞等。 - 保存模型并应用于新的图像。 希望这可以帮助您开始使用PyTorch实现UNet图像分割

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值