Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Apply ColorMap with OpenCV?

Description

I am trying to convert a numpy array and then, apply a color map to a 2d numpy array that’s filled with float values between 0 – 1. I have written this piece of code for that:

for i in range(arr.shape[0]):

    for j in range(arr.shape[1]):

        arr[i,j] = arr[i,j] * 255
        arr[i,j] = int(round(arr[i,j]))
        
arr.astype(np.uint8)
colorMapImage = cv2.cvtColor(arr,cv2.COLOR_GRAY2BGR)
colorMapImage = cv2.applyColorMap(colorMapImage, cv2.COLORMAP_VIRIDIS)

But, when I try to run the code I see the following error:

[ERROR] [1719390004.370940]: Error processing image: OpenCV(4.2.0) /home/myPC/opencv_build/opencv/modules/imgproc/src/colormap.cpp:714: error: (-5:Bad argument) cv::ColorMap only supports source images of type CV_8UC1 or CV_8UC3 in function 'operator()'

Notes

  1. The numpy array was normalized to interval 0 – 1 before the conversion to OpenCV image.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  2. Shape of arr is (300, 300)

  3. When I print colorMapImage[0,0] just before applying color map, It prints: [5. 5. 5.]

  4. When I print out arr.dtype(), I see the following error:

    Error processing image: 'numpy.dtype[float32]' object is not callable

  5. When I print types of both arr and colorMapImage with print(str(type())), it prints, <class ‘numpy.ndarray’> for both.

>Solution :

The arr numpy array is not being correctly converted to an 8-bit unsigned integer (np.uint8) before applying the color map. The conversion to np.uint8 is attempted, but the result is not stored back into arr. There also seems to be a minor mistake in how you’re trying to print the data type of arr.

import numpy as np
import cv2

arr = (arr * 255).round().astype(np.uint8)
colorMapImage = cv2.cvtColor(arr, cv2.COLOR_GRAY2BGR)
colorMapImage = cv2.applyColorMap(colorMapImage, cv2.COLORMAP_VIRIDIS)
print(arr.dtype)
print(colorMapImage[0, 0])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading