Cristiano Araujo
Cristiano Araujo

Reputation: 1962

Applying matplotlib color map to opencv image

I'm trying to apply a colormap from matplotlib to a OpenCv Image (I know I can use other libraries, but I'm using OpenCv for other things).

I can apply it and show it with the following script:

import cv2
from matplotlib.pylab import cm

def colorize(image, colormap):
    im = cv2.imread(image)
    im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    colorized = colormap(im)
    cv2.imshow("colorized", colorized)
    cv2.waitKey(0)
    cv2.imwrite("colorized.jpg", colorized)

if __name__ == "__main__":
    import sys
    colorize(sys.argv[1], cm.jet)

It does fine, but the "colorized.jpg" image is black.

I suppose I have to convert it from a 3 color + alpha channel to a 3 channel image, but no idea how.

Is there a way to save the image shown in the imshow() call correctly ?

Upvotes: 3

Views: 6858

Answers (1)

hitzg
hitzg

Reputation: 12701

imwrite expects color values in the range [0,255]. However, the colormap returns color values in the range [0,1]. Thus, this gives the desired result:

cv2.imwrite("colorized.jpg", colorized*255)

Upvotes: 3

Related Questions