4

What would be the equivalent of imagesc in OpenCV?

Rahul
  • 1,495
  • 1
  • 15
  • 25

2 Answers2

7

To get the nice colors in imagesc you have to play around with OpenCV a little bit. In OpenCV 2.46 there ss a colormap option.

This is code I use in c++. Im sure its very similar in Python.

mydata.convertTo(display, CV_8UC1, 255.0 / 10000.0, 0); 
applyColorMap(display, display, cv::COLORMAP_JET);
imshow("imagesc",display);

The image data or matrix data is stored in mydata. I know that it has a maximum value of 10000 so I scale it down to 1 and then multiply by the range of CV_8UC1 which is 255. If you dont know what the range is the best option is to first convert your matrix in the same way as Matlab does it.

EDIT

Here is a version which automatically normalizes your data.

float Amin = *min_element(mydata.begin<float>(), mydata.end<float>());
float Amax = *max_element(mydata.begin<float>(), mydata.end<float>());
Mat A_scaled = (mydata - Amin)/(Amax - Amin);
A_scaled.convertTo(display, CV_8UC1, 255.0, 0); 
applyColorMap(display, display, cv::COLORMAP_JET);
imshow("imagesc",display);
Community
  • 1
  • 1
twerdster
  • 4,977
  • 3
  • 40
  • 70
  • 1
    +1 perhaps you should generalize the code by using [`cv::normalize`](http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize) to normalize the image to the range of its data type, just like you did in MATLAB in the linked post – Amro Sep 23 '13 at 09:06
  • 1
    @twerdtser: I think you should changed by `Mat A_scaled = (mydata - Amin)/(Amax - Amin)` – Katsu Sep 24 '13 at 08:27
2

It's close to imshow in matlab.

It depends on modules you use in python:

import cv2
import cv2.cv as cv

I_cv2 = cv2.imread("image.jpg")
I_cv = cv.LoadImage("image.jpg")

#I_cv2 is numpy.ndarray norm can be done easily
I_cv2_norm = (I_cv2-I_cv2.min())/(I_cv2.max()-I_cv2.min())
cv2.imshow("cv2Im scaled", I_cv2_norm)

#Here you have to normalize your cv iplimage as explain by twerdster to norm
cv.ShowImage("cvIm unscaled",I_cv)

The best way I think to be close to imagesc, is to use cv2.imread which load image as numpy.ndarray and next use imshow function from matplotlib.pyplot module:

import cv2
from matplolib.pyplot import imshow, show
I = cv2.imread("path")
#signature:
imshow(I, cmap=None, norm=None, aspect=None, interpolation=None,
             alpha=None, vmin=None, vmax=None, origin=None, extent=None,
             **kwargs)

Here you can choose whatever you want if normalized or your clims (scale)...

Katsu
  • 1,868
  • 4
  • 19
  • 28
  • note that `imagesc` will also appropriately scale the image. Say in OpenCV you have a `CV_64F` image with values outside the range `[0,1]`, you'll need to map them to the expected range before showing the image – Amro Sep 22 '13 at 20:29