You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何显示并保存图像翻转函数处理后的图像与掩码?

图像与掩码翻转后的显示与保存方案

首先先修正你代码里的两个小问题:

  1. Load_Image函数里的cv.imread要改为cv2.imread(你导入的是cv2而非cv)
  2. 调用翻转函数时,变量名不要和函数名重名,否则会覆盖原函数,建议改为:
    flipped_img, flipped_mask = RandomFlip(img, msk)
    

一、显示翻转后的图像

提供两种常用方案,适配不同查看需求:

方案1:用Matplotlib并排对比显示

适合快速查看图像与掩码的对应关系,代码如下:

# 创建1行2列的子图布局,控制显示尺寸
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

# 显示翻转后的图像
ax1.imshow(flipped_img)
ax1.set_title('翻转后的图像')
ax1.axis('off')  # 隐藏坐标轴,让画面更整洁

# 显示翻转后的掩码(掩码一般用灰度图显示更清晰)
ax2.imshow(flipped_mask, cmap='gray')
ax2.set_title('翻转后的掩码')
ax2.axis('off')

# 自动调整子图间距
plt.tight_layout()
plt.show()

方案2:用OpenCV单独弹窗显示

OpenCV的窗口支持拖拽缩放,适合细节查看,注意要把RGB转回BGR格式(OpenCV默认以BGR读取/显示):

# 图像转回BGR格式后显示
cv2.imshow('Flipped Image', flipped_img[:, :, ::-1])
# 掩码如果是多通道同样转回BGR,单通道直接显示
cv2.imshow('Flipped Mask', flipped_mask[:, :, ::-1] if len(flipped_mask.shape)==3 else flipped_mask)

# 等待任意按键关闭窗口,0表示无限等待
cv2.waitKey(0)
cv2.destroyAllWindows()

二、保存翻转后的图像

提供两种方案,适配不同后续处理场景:

方案1:用OpenCV保存(通用格式)

同样需要转回BGR格式,避免保存的图像颜色异常:

# 保存翻转后的图像
cv2.imwrite('flipped_6192.jpg', flipped_img[:, :, ::-1])
# 保存翻转后的掩码
cv2.imwrite('flipped_6192.bmp', flipped_mask[:, :, ::-1] if len(flipped_mask.shape)==3 else flipped_mask)

方案2:用Torch的save_image保存(适配PyTorch流程)

如果后续需要用PyTorch处理,可以直接转为张量保存:

# 将图像从HWC格式转为CHW张量,并增加batch维度
img_tensor = transforms.ToTensor()(flipped_img).unsqueeze(0)
mask_tensor = transforms.ToTensor()(flipped_mask).unsqueeze(0)

# 保存张量格式的图像
save_image(img_tensor, 'flipped_tensor_6192.jpg')
save_image(mask_tensor, 'flipped_tensor_6192.bmp')

修正后的完整代码示例

import torch
import torchvision.transforms as transforms
from torchvision.utils import save_image
import cv2 
from matplotlib import pyplot as plt
import numpy as np

## define functions
def t_random(min=0, max=1):
    return min + (max - min) * np.random.rand()

def t_randint(min, max):
    return np.random.randint(low=min, high=max)

class augCompose(object):
    def __init__(self, transforms=None):
        self.transforms = transforms

    def __call__(self, img, mask):
        if self.transforms is not None:
            for op, prob in self.transforms:
                if t_random() <= prob:
                    img, mask = op(img, mask)
        return img, mask

def RandomFlip(img, mask, FLIP_LEFT_RIGHT=True, FLIP_TOP_BOTTOM=True):
    if FLIP_LEFT_RIGHT and t_random() < 0.5:
        img = cv2.flip(img, 1)
        mask = cv2.flip(mask, 1)
    if FLIP_TOP_BOTTOM and t_random() < 0.5:
        img = cv2.flip(img, 0)
        mask = cv2.flip(mask, 0)
    return img, mask

# This function will read the image using its path with opencv
def Load_Image(Path):
    img = cv2.imread(Path)[:,:,::-1] # opencv read the images in BGR format 
                                    # so we use [:,:,::-1] to convert from BGR to RGB
    return img

## Load the image
img = Load_Image("..........\\6192.jpg")
msk = Load_Image("...........\\6192.bmp")

## Call the function 
flipped_img, flipped_mask = RandomFlip(img, msk)

## 显示图像
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
ax1.imshow(flipped_img)
ax1.set_title('翻转后的图像')
ax1.axis('off')
ax2.imshow(flipped_mask, cmap='gray')
ax2.set_title('翻转后的掩码')
ax2.axis('off')
plt.tight_layout()
plt.show()

## 保存图像
cv2.imwrite('flipped_6192.jpg', flipped_img[:, :, ::-1])
cv2.imwrite('flipped_6192.bmp', flipped_mask[:, :, ::-1] if len(flipped_mask.shape)==3 else flipped_mask)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:31:21