Raquel
Raquel

Reputation: 165

how to apply colormap to grayscale data, with OpenCV

I have a np.array with grayscale images and I want to apply a colormap, then save the result into a video file.

With this code (or with the commented line) I get a grayscale video anyways. Any idea why I can't have a colormap video?

color_images = np.empty([N, resolution[1], resolution[0], 3])
for i in range(0, N):
    cv2.imwrite(gray_images[i])
    color_images[i] = cv2.cvtColor(np.float32(gray_images[i]), cv2.COLOR_GRAY2BGR)
    #color_images[i] = cv2.merge([gray_images[i], gray_images[i], gray_images[i]])
out = cv2.VideoWriter("video.mp4", cv2.VideoWriter_fourcc(*'mp4v'),
                      fps, (resolution[0], resolution[1]), 1)
for i in range(0, N):
    out.write(np.uint8(color_images[i]))
out.release()

UPDATE: I want to have a colored image so that differences in pixel intensity can be more noticeable. (For instance use the default cmap in plt.imshow ('viridis')).

Upvotes: 3

Views: 5153

Answers (3)

pchatla
pchatla

Reputation: 1

import cv2

im = cv2.imread("flower.jpg")

gray_scale = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

cv2.applyColorMap(gray_scale, cv2.COLORMAP_JET)

The available color maps:

Color Maps

Upvotes: 0

Talha Ilyas
Talha Ilyas

Reputation: 151

OpenCV (cv2) can apply a colormap to an image and save it. However, OpenCV's colormap functions expect the image data to be in 8-bit format, so you'll need to scale your normalized depth map to the range [0, 255] and convert it to an 8-bit format before applying the colormap. So in case you have floating point precision data and you want to apply colormap on that use matplotlib. A simple use case

import matplotlib.pyplot as plt
import matplotlib.cm as cm

# Normalize the depth map
depth_map_normalized = np.clip(depth_map / 65000.0, 0, 1)

# Apply a colormap
depth_map_colored = cm.jet(depth_map_normalized)

# Save the result
plt.imsave('depth_map_colored.png', depth_map_colored)

Upvotes: 0

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15517

cvtColor doesn't do that. For any grayscale pixel, it gives you the RGB/BGR pixel that looks gray with the same intensity.

If you want colormaps, you need applyColorMap.

import numpy as np
import cv2 as cv

gray_image = ... # get it from somewhere

colormapped_image = cv.applyColorMap(gray_image, cv.COLORMAP_JET)

lena and COLORMAP_JET

learn more here

Upvotes: 3

Related Questions