4

I am trying to read and display a tiff image with opencv. I tried different reading modes in imread (-1,0,1,2) The result of the code below displays the image wrongly as blue only while it is colored.

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)

Original image:

[original]

Displayed blue image of the code :

[blue]

Tim
  • 10,459
  • 4
  • 36
  • 47
partizanos
  • 1,064
  • 12
  • 22
  • will try it within the day and let you know if it is working, nonetheless thanks a lot – partizanos Apr 29 '19 at 08:54
  • rgb = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) plt.imshow(rgb, cmap = plt.cm.Spectral) This worked while cv2.imshow('image',im) opens a new window running from jupyter in pycharm. Stil thanks a lot for your help and the working solution. PS what cv2 version are u using? – partizanos Apr 29 '19 at 22:16
  • you're welcome. I am using opencv 3.3.1-dev – Tim Apr 30 '19 at 05:18

1 Answers1

8

The problem is that opencv uses bgr color mode and matplotlib uses rgb color mode. Therefore the red and blue color channels are switched.

You can easily fix that problem by proving matplotlib an rgb image or by using cv2.imshow function.

  1. BGR to RGB conversion:

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

    for im in images:
        # no color conversion needed, because bgr is also used by imshow
        cv2.imshow('image',im)
    
Tim
  • 10,459
  • 4
  • 36
  • 47