xiaomoguhzz's picture
Add files using upload-large-folder tool
34e7ef3 verified
import json
import openpyxl
import numpy as np
import torch
import cv2
from PIL import Image
import os
def convert_to_numpy(input_data):
"""
将输入转换为 NumPy 数组。如果输入是 PyTorch Tensor,先将其转为 NumPy。
参数:
input_data (torch.Tensor 或 numpy.ndarray): 输入的张量或 NumPy 数组。
返回:
numpy.ndarray: 转换后的 NumPy 数组。
"""
if isinstance(input_data, torch.Tensor):
return input_data.squeeze().cpu().numpy()
elif isinstance(input_data, np.ndarray):
return input_data
else:
raise TypeError("输入必须是 PyTorch Tensor 或 NumPy 数组")
def calculate_image_mIoU(gt_mask, pred_mask):
"""
计算单张图片的 mIoU (mean Intersection over Union),只考虑当前图片中的实际类别。
参数:
gt_mask (torch.Tensor 或 numpy.ndarray): ground truth 掩码 (H, W),忽略区域为 255。
pred_mask (torch.Tensor 或 numpy.ndarray): 预测的掩码 (H, W),忽略区域为 255。
返回:
mIoU (float): 当前图片的 mIo(只考虑实际存在的类别)。
"""
# 将输入转换为 NumPy 数组
gt_mask = convert_to_numpy(gt_mask)
pred_mask = convert_to_numpy(pred_mask)
# 获取当前图片中实际存在的类别(排除 255,代表忽略的像素)
unique_classes = np.unique(gt_mask)
unique_classes = unique_classes[unique_classes != 255] # 排除 255
# 初始化 IoU 列表
ious = []
for cls in unique_classes:
# 计算交集和并集
intersection = np.logical_and(pred_mask == cls, gt_mask == cls).sum()
union = np.logical_or(pred_mask == cls, gt_mask == cls).sum()
if union == 0:
# 如果该类在 GT 和预测中都不存在,跳过
ious.append(np.nan) # 该类 IoU 记为 NaN
else:
iou = intersection / union
ious.append(iou)
# 如果当前图片没有有效的类别,返回 NaN
if len(ious) == 0:
return np.nan
# 计算 mIoU,忽略 NaN 值
mIoU = np.nanmean(ious)
return mIoU
class UnNormalize(object):
def __init__(self, mean, std):
self.mean = mean
self.std = std
def __call__(self, image):
image2 = torch.clone(image)
for t, m, s in zip(image2, self.mean, self.std):
t.mul_(s).add_(m)
return image2
def append_experiment_result(file_path, experiment_data):
try:
workbook = openpyxl.load_workbook(file_path)
except FileNotFoundError:
workbook = openpyxl.Workbook()
sheet = workbook.active
if sheet['A1'].value is None:
sheet['B1'] = 'CLIP'
sheet['D1'] = 'Dataset'
sheet['E1'] = 'aAcc'
sheet['F1'] = 'mIoU'
sheet['G1'] = 'mAcc'
last_row = sheet.max_row
for index, result in enumerate(experiment_data, start=1):
sheet.cell(row=last_row + index, column=2, value=result['CLIP'])
sheet.cell(row=last_row + index, column=4, value=result['Dataset'])
sheet.cell(row=last_row + index, column=5, value=result['aAcc'])
sheet.cell(row=last_row + index, column=6, value=result['mIoU'])
sheet.cell(row=last_row + index, column=7, value=result['mAcc'])
workbook.save(file_path)
def visualize_voc_context59(batch_img_metas, result):
# PASCAL Context 59 调色盘
palette = [[180, 120, 120], [6, 230, 230], [80, 50, 50],
[4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
[230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
[150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
[143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
[0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
[255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
[255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
[255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
[224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
[255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
[6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
[140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
[255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
[255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255]]
# 获取 ground truth 和 prediction mask
gt_mask = result[0].gt_sem_seg.data.squeeze().cpu().numpy() # (H, W)
pred_mask = result[0].pred_sem_seg.data.squeeze().cpu().numpy() # (H, W)
# 读取原图
img_path = batch_img_metas[0]['img_path']
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换为RGB格式
print(img_path)
exit(0)
# 忽略 GT mask 中为 255 的区域
pred_mask[gt_mask == 255] = 255 # 将预测结果中 GT 为 255 的地方也设为 255 (ignore)
# iou=calculate_image_mIoU(pred_mask,gt_mask)
# 函数:将mask转换为彩色图像
def apply_palette(mask, palette):
color_mask = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)
for label, color in enumerate(palette):
# 忽略255的区域,只映射有效类别
if label < 255:
color_mask[mask == label] = color
return color_mask
# 将预测和GT mask应用调色盘
pred_color_mask = apply_palette(pred_mask, palette)
gt_color_mask = apply_palette(gt_mask, palette)
# 将原图与mask叠加
def overlay_image(img, mask, alpha=0.5):
return cv2.addWeighted(img, 1 - alpha, mask, alpha, 0)
# 叠加 mask 到原图上
pred_overlay = overlay_image(img, pred_color_mask)
gt_overlay = overlay_image(img, gt_color_mask)
# 保存路径
out_path = '/mnt/SSD8T/home/wjj/code/ProxyCLIP/visualize_clearclip'
if not os.path.exists(out_path):
os.mkdir(out_path)
# json_save_path = os.path.join(out_path, 'results_clearclip.json')
# results={os.path.basename(img_path):iou}
# # 检查 JSON 文件是否存在
# if os.path.exists(json_save_path):
# with open(json_save_path, 'r') as f:
# existing_results = json.load(f)
# else:
# existing_results = {}
# existing_results.update(results)
# with open(json_save_path, 'w') as f:
# json.dump(existing_results, f, indent=4)
pred_save_path = os.path.join(out_path, os.path.basename(img_path).replace('.jpg', '_pred.png'))
gt_save_path = os.path.join(out_path, os.path.basename(img_path).replace('.jpg', '_gt.png'))
# 保存图片
Image.fromarray(pred_overlay).save(pred_save_path)
Image.fromarray(gt_overlay).save(gt_save_path)
def visualize_ade20k(batch_img_metas, result):
# ADE20K 类别名
classes = ('wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road',
'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk',
'person', 'earth', 'door', 'table', 'mountain', 'plant',
'curtain', 'chair', 'car', 'water', 'painting', 'sofa',
'shelf', 'house', 'sea', 'mirror', 'rug', 'field', 'armchair',
'seat', 'fence', 'desk', 'rock', 'wardrobe', 'lamp',
'bathtub', 'railing', 'cushion', 'base', 'box', 'column',
'signboard', 'chest of drawers', 'counter', 'sand', 'sink',
'skyscraper', 'fireplace', 'refrigerator', 'grandstand',
'path', 'stairs', 'runway', 'case', 'pool table', 'pillow',
'screen door', 'stairway', 'river', 'bridge', 'bookcase',
'blind', 'coffee table', 'toilet', 'flower', 'book', 'hill',
'bench', 'countertop', 'stove', 'palm', 'kitchen island',
'computer', 'swivel chair', 'boat', 'bar', 'arcade machine',
'hovel', 'bus', 'towel', 'light', 'truck', 'tower',
'chandelier', 'awning', 'streetlight', 'booth',
'television receiver', 'airplane', 'dirt track', 'apparel',
'pole', 'land', 'bannister', 'escalator', 'ottoman', 'bottle',
'buffet', 'poster', 'stage', 'van', 'ship', 'fountain',
'conveyer belt', 'canopy', 'washer', 'plaything',
'swimming pool', 'stool', 'barrel', 'basket', 'waterfall',
'tent', 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food',
'step', 'tank', 'trade name', 'microwave', 'pot', 'animal',
'bicycle', 'lake', 'dishwasher', 'screen', 'blanket',
'sculpture', 'hood', 'sconce', 'vase', 'traffic light',
'tray', 'ashcan', 'fan', 'pier', 'crt screen', 'plate',
'monitor', 'bulletin board', 'shower', 'radiator', 'glass',
'clock', 'flag')
# ADE20K 调色盘
palette = [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],
[4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
[230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
[150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
[143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
[0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
[255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
[255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
[255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
[224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
[255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
[6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
[140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
[255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
[255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],
[11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],
[0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],
[255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],
[0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],
[173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],
[255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],
[255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],
[255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],
[0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],
[0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],
[143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],
[8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],
[255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],
[92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],
[163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],
[255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],
[255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],
[10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],
[255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],
[41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],
[71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],
[184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],
[102, 255, 0], [92, 0, 255]]
# 获取 ground truth 和 prediction mask
gt_mask = result[0].gt_sem_seg.data.squeeze().cpu().numpy() # (H, W)
pred_mask = result[0].pred_sem_seg.data.squeeze().cpu().numpy() # (H, W)
# 读取原图
img_path = batch_img_metas[0]['img_path']
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换为RGB格式
# 忽略 GT mask 中为 255 的区域
pred_mask[gt_mask == 255] = 255 # 将预测结果中 GT 为 255 的地方也设为 255 (ignore)
# iou=calculate_image_mIoU(pred_mask,gt_mask)
# 函数:将mask转换为彩色图像
def apply_palette(mask, palette):
color_mask = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)
for label, color in enumerate(palette):
if label < 255:
color_mask[mask == label] = color
return color_mask
# 将预测和GT mask应用调色盘
pred_color_mask = apply_palette(pred_mask, palette)
gt_color_mask = apply_palette(gt_mask, palette)
# 将原图与mask叠加
def overlay_image(img, mask, alpha=0.6):
return cv2.addWeighted(img, 1 - alpha, mask, alpha, 0)
# 叠加 mask 到原图上
pred_overlay = overlay_image(img, pred_color_mask)
gt_overlay = overlay_image(img, gt_color_mask)
# 保存路径
out_path = '/mnt/SSD8T/home/wjj/code/ProxyCLIP/visualize'
if not os.path.exists(out_path):
os.mkdir(out_path)
# json_save_path = os.path.join(out_path, 'ADE_DeCLIP.json')
# results={os.path.basename(img_path):iou}
# # 检查 JSON 文件是否存在
# if os.path.exists(json_save_path):
# with open(json_save_path, 'r') as f:
# existing_results = json.load(f)
# else:
# existing_results = {}
# existing_results.update(results)
# with open(json_save_path, 'w') as f:
# json.dump(existing_results, f, indent=4)
pred_save_path = os.path.join(out_path, os.path.basename(img_path).replace('.jpg', '_pred.png'))
gt_save_path = os.path.join(out_path, os.path.basename(img_path).replace('.jpg', '_gt.png'))
# 保存图片
Image.fromarray(pred_overlay).save(pred_save_path)
Image.fromarray(gt_overlay).save(gt_save_path)
def visualize_coco_stuff(batch_img_metas, result):
# COCO-Stuff 171 类别名
classes = (
'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
'hair drier', 'toothbrush', 'banner', 'blanket', 'branch', 'bridge', 'building-other', 'bush', 'cabinet',
'cage', 'cardboard', 'carpet', 'ceiling-other', 'ceiling-tile', 'cloth', 'clothes', 'clouds', 'counter',
'cupboard', 'curtain', 'desk-stuff', 'dirt', 'door-stuff', 'fence', 'floor-marble', 'floor-other',
'floor-stone', 'floor-tile', 'floor-wood', 'flower', 'fog', 'food-other', 'fruit', 'furniture-other',
'grass', 'gravel', 'ground-other', 'hill', 'house', 'leaves', 'light', 'mat', 'metal', 'mirror-stuff', 'moss',
'mountain', 'mud', 'napkin', 'net', 'paper', 'pavement', 'pillow', 'plant-other', 'plastic', 'platform',
'playingfield', 'railing', 'railroad', 'river', 'road', 'rock', 'roof', 'rug', 'salad', 'sand', 'sea', 'shelf',
'sky-other', 'skyscraper', 'snow', 'solid-other', 'stairs', 'stone', 'straw', 'structural-other', 'table',
'tent', 'textile-other', 'towel', 'tree', 'vegetable', 'wall-brick', 'wall-concrete', 'wall-other',
'wall-panel', 'wall-stone', 'wall-tile', 'wall-wood', 'water-other', 'waterdrops', 'window-blind',
'window-other', 'wood'
)
# COCO-Stuff 171 调色盘
palette = [[0, 192, 64], [0, 192, 64], [0, 64, 96], [128, 192, 192], [0, 64, 64], [0, 192, 224], [0, 192, 192],
[128, 192, 64], [0, 192, 96], [128, 192, 64], [128, 32, 192], [0, 0, 224], [0, 0, 64], [0, 160, 192],
[128, 0, 96], [128, 0, 192], [0, 32, 192], [128, 128, 224], [0, 0, 192], [128, 160, 192], [128, 128, 0],
[128, 0, 32], [128, 32, 0], [128, 0, 128], [64, 128, 32], [0, 160, 0], [0, 0, 0], [192, 128, 160],
[0, 32, 0], [0, 128, 128], [64, 128, 160], [128, 160, 0], [0, 128, 0], [192, 128, 32], [128, 96, 128],
[0, 0, 128], [64, 0, 32], [0, 224, 128], [128, 0, 0], [192, 0, 160], [0, 96, 128], [128, 128, 128],
[64, 0, 160], [128, 224, 128], [128, 128, 64], [192, 0, 32], [128, 96, 0], [128, 0, 192], [0, 128, 32],
[64, 224, 0], [0, 0, 64], [128, 128, 160], [64, 96, 0], [0, 128, 192], [0, 128, 160], [192, 224, 0],
[0, 128, 64], [128, 128, 32], [192, 32, 128], [0, 64, 192], [0, 0, 32], [64, 160, 128], [128, 64, 64],
[128, 0, 160], [64, 32, 128], [128, 192, 192], [0, 0, 160], [192, 160, 128], [128, 192, 0], [128, 0, 96],
[192, 32, 0], [128, 64, 128], [64, 128, 96], [64, 160, 0], [0, 64, 0], [192, 128, 224], [64, 32, 0],
[0, 192, 128], [64, 128, 224], [192, 160, 0], [0, 192, 0], [192, 128, 96], [192, 96, 128], [0, 64, 128],
[64, 0, 96], [64, 224, 128], [128, 64, 0], [192, 0, 224], [64, 96, 128], [128, 192, 128], [64, 0, 224],
[192, 224, 128], [128, 192, 64], [192, 0, 96], [192, 96, 0], [128, 64, 192], [0, 128, 96], [0, 224, 0],
[64, 64, 64], [128, 128, 224], [0, 96, 0], [64, 192, 192], [0, 128, 224], [128, 224, 0], [64, 192, 64],
[128, 128, 96], [128, 32, 128], [64, 0, 192], [0, 64, 96], [0, 160, 128], [192, 0, 64], [128, 64, 224],
[0, 32, 128], [192, 128, 192], [0, 64, 224], [128, 160, 128], [192, 128, 0], [128, 64, 32], [128, 32, 64],
[192, 0, 128], [64, 192, 32], [0, 160, 64], [64, 0, 0], [192, 192, 160], [0, 32, 64], [64, 128, 128],
[64, 192, 160], [128, 160, 64], [64, 128, 0], [192, 192, 32], [128, 96, 192], [64, 0, 128], [64, 64, 32],
[0, 224, 192], [192, 0, 0], [192, 64, 160], [0, 96, 192], [192, 128, 128], [64, 64, 160], [128, 224, 192],
[192, 128, 64], [192, 64, 32], [128, 96, 64], [192, 0, 192], [0, 192, 32], [64, 224, 64], [64, 0, 64],
[128, 192, 160], [64, 96, 64], [64, 128, 192], [0, 192, 160], [192, 224, 64], [64, 128, 64], [128, 192, 32],
[192, 32, 192], [64, 64, 192], [0, 64, 32], [64, 160, 192], [192, 64, 64], [128, 64, 160], [64, 32, 192],
[192, 192, 192], [0, 64, 160], [192, 160, 192], [192, 192, 0], [128, 64, 96], [192, 32, 64], [192, 64, 128],
[64, 192, 96], [64, 160, 64], [64, 64, 0]]
# 获取 ground truth 和 prediction mask
gt_mask = result[0].gt_sem_seg.data.squeeze().cpu().numpy() # (H, W)
pred_mask = result[0].pred_sem_seg.data.squeeze().cpu().numpy() # (H, W)
# 读取原图
img_path = batch_img_metas[0]['img_path']
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换为RGB格式
# 忽略 GT mask 中为 255 的区域
pred_mask[gt_mask == 255] = 255 # 将预测结果中 GT 为 255 的地方也设为 255 (ignore)
# iou=calculate_image_mIoU(pred_mask,gt_mask)
# 函数:将mask转换为彩色图像
def apply_palette(mask, palette):
color_mask = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)
for label, color in enumerate(palette):
# 忽略255的区域,只映射有效类别
if label < 255:
color_mask[mask == label] = color
return color_mask
# 将预测和GT mask应用调色盘
pred_color_mask = apply_palette(pred_mask, palette)
gt_color_mask = apply_palette(gt_mask, palette)
# 将原图与mask叠加
def overlay_image(img, mask, alpha=0.7):
return cv2.addWeighted(img, 1 - alpha, mask, alpha, 0)
# 叠加 mask 到原图上
pred_overlay = overlay_image(img, pred_color_mask)
gt_overlay = overlay_image(img, gt_color_mask)
out_path = '/mnt/SSD8T/home/wjj/code/ProxyCLIP/ClearCLIP_stuff'
if not os.path.exists(out_path):
os.mkdir(out_path)
# start JSON PART
# json_save_path = os.path.join(out_path, 'Stuff_ClearCLIP.json')
# results={os.path.basename(img_path):iou}
# # 检查 JSON 文件是否存在
# if os.path.exists(json_save_path):
# with open(json_save_path, 'r') as f:
# existing_results = json.load(f)
# else:
# existing_results = {}
# existing_results.update(results)
# with open(json_save_path, 'w') as f:
# json.dump(existing_results, f, indent=4)
# end JSON PART
pred_save_path = os.path.join(out_path, os.path.basename(img_path).replace('.jpg', '_pred.png'))
gt_save_path = os.path.join(out_path, os.path.basename(img_path).replace('.jpg', '_gt.png'))
if 15 in gt_mask:
# 保存图片
Image.fromarray(pred_overlay).save(pred_save_path)
Image.fromarray(gt_overlay).save(gt_save_path)
def visualize_cityscapes(batch_img_metas, result):
# Cityscapes 调色盘
palette = [[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156],
[190, 153, 153], [153, 153, 153], [250, 170, 30], [220, 220, 0],
[107, 142, 35], [152, 251, 152], [70, 130, 180],
[220, 20, 60], [255, 0, 0], [0, 0, 142], [0, 0, 70],
[0, 60, 100], [0, 80, 100], [0, 0, 230], [119, 11, 32]]
# 获取 ground truth 和 prediction mask
gt_mask = result[0].gt_sem_seg.data.squeeze().cpu().numpy() # (H, W)
pred_mask = result[0].pred_sem_seg.data.squeeze().cpu().numpy() # (H, W)
# 读取原图
img_path = batch_img_metas[0]['img_path']
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 转换为RGB格式
# 忽略 GT mask 中为 255 的区域
pred_mask[gt_mask == 255] = 255 # 将预测结果中 GT 为 255 的地方也设为 255 (ignore)
# iou=calculate_image_mIoU(pred_mask,gt_mask)
# 函数:将mask转换为彩色图像
def apply_palette(mask, palette):
color_mask = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)
for label, color in enumerate(palette):
# 忽略255的区域,只映射有效类别
if label < 255:
color_mask[mask == label] = color
return color_mask
# 将预测和GT mask应用调色盘
pred_color_mask = apply_palette(pred_mask, palette)
gt_color_mask = apply_palette(gt_mask, palette)
# 将原图与mask叠加
def overlay_image(img, mask, alpha=0.7):
return cv2.addWeighted(img, 1 - alpha, mask, alpha, 0)
# 叠加 mask 到原图上
pred_overlay = overlay_image(img, pred_color_mask)
gt_overlay = overlay_image(img, gt_color_mask)
# 缩小四倍
h, w = pred_overlay.shape[:2]
new_size = (w // 4, h // 4)
pred_overlay_resized = cv2.resize(pred_overlay, new_size, interpolation=cv2.INTER_AREA)
gt_overlay_resized = cv2.resize(gt_overlay, new_size, interpolation=cv2.INTER_AREA)
# 保存路径
out_path = '/mnt/SSD8T/home/wjj/code/ProxyCLIP/visualization'
if not os.path.exists(out_path):
os.mkdir(out_path)
# start JSON PART
# json_save_path = os.path.join(out_path, 'city_ClearCLIP.json')
# results={os.path.basename(img_path):iou}
# # 检查 JSON 文件是否存在
# if os.path.exists(json_save_path):
# with open(json_save_path, 'r') as f:
# existing_results = json.load(f)
# else:
# existing_results = {}
# existing_results.update(results)
# with open(json_save_path, 'w') as f:
# json.dump(existing_results, f, indent=4)
# end JSON PART
pred_save_path = os.path.join(out_path, os.path.basename(img_path).replace('.png', '_pred.png'))
gt_save_path = os.path.join(out_path, os.path.basename(img_path).replace('.png', '_gt.png'))
# 保存缩小后的图片
Image.fromarray(pred_overlay_resized).save(pred_save_path)
Image.fromarray(gt_overlay_resized).save(gt_save_path)
if __name__=="__main__":
visualize_voc_context59(None)