imshow 彩色图像,错误显示为蓝色

imshow colored image, wrongly displayed as blue

我正在尝试使用 opencv 读取和显示 tiff 图像。 我在 imread (-1,0,1,2) 中尝试了不同的阅读模式 以下代码的结果仅在彩色时将图像错误地显示为蓝色。

import numpy as np
import cv2 
import matplotlib.pyplot as plt
def readImagesAndTimes():
  # List of exposure times
  times = np.array([ 1/30.0, 0.25, 2.5, 15.0 ], dtype=np.float32)

  # List of image filenames
  filenames = ["img01.tif", "img02.tif", "img03.tif", "img04.tif", "img05.tif"]
  images = []
  for filename in filenames:
    im = cv2.imread("./data/hdr_images/" + filename, -1)
    images.append(im)

  return images, times

images, times = readImagesAndTimes()
for im in images:
    print(im.shape)
    plt.imshow(im, cmap = plt.cm.Spectral)

原图:

[]

显示代码的蓝色图像:

[]

问题是opencv使用bgr颜色模式而matplotlib使用rgb颜色模式。因此,红色和蓝色通道被切换。

您可以通过证明 matplotlib 为 rgb 图像或使用 cv2.imshow 函数轻松解决该问题。

  1. BGR 到 RGB 转换:

    for im in images:
        # convert bgr to rgb 
        rgb = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
        plt.imshow(rgb, cmap = plt.cm.Spectral)
    
  2. opencv的imshow函数:

    for im in images:
        # no color conversion needed, because bgr is also used by imshow
        cv2.imshow('image',im)