python_opencv和plt加载图像

OpenCv以彩色图片的形式加载的图片是BGR模式。但是在Matplotlib中,是以RGB的模式加载的。

使用OpenCv保存深度学习数据集中的RGB图像需要交换通道才能正常使用。

    for imgs, dpts in test_loader:
        if torch.cuda.is_available():
            imgs = imgs.cuda()
            dpts = dpts.cuda()

        img_cv = imgs[0].data.cpu()
        t0 = img_cv[0].clone()
        t2 = img_cv[2].clone()
        img_cv[0] = t2
        img_cv[2] = t0
        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #将图像从opencv的brg通道转为matplotlib的rgb模式,找到一种新写法

        # permute(1, 2, 0), 图像(CHW) -> (HWC), 将pytorch处理图像的模式是前者
        img_cv = img_cv.permute(1, 2, 0).numpy() * 255.0 #交换通道后,像素值(0,1)->(0, 255)
        print(img_cv.shape)
        cv.imwrite('./test/img_cv.png', img_cv)

        img = imgs[0].data.cpu().permute(1, 2, 0).cpu().numpy()
        # print(img.shape)
        plt.imshow(img)
        plt.show()

        break

猜你喜欢

转载自blog.csdn.net/Gentlemanman/article/details/86540299