简体   繁体   中英

convert a 2D numpy array with positive and negative values, into an RGB images

enter image description here I'have a 2D numpy array (128 x 128) with values positive and negatives. I want to convert it into an RGB image. My idea is that each pixel in the image has a colour according to the value (eg negative values have a colour towards blue and red for positive values). I thought this would be automatic when I converted into an RGB image but it kept on being grey. The images in the link is an example, it is in greyscale,but i want to add colors

image = (image - image.min()) / (image.max() - image.min()) #to normalize
image = (image * 255).astype(np.uint8)
image = Image.fromarray(image, 'L').convert('RGB')

Each pixel value is duplicated when converting from a gray image to an RGB image. So it still looks like a grayscale image.

I will briefly show you an example.

import cv2
import numpy as np
from matplotlib import pyplot as plt

image = np.random.rand(28, 28)
image = (image - image.min()) / (image.max() - image.min()) #to normalize
image = (image * 255).astype(np.uint8)

print(image[0][0]) #100

image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)

image[0][0] #[100, 100, 100]

The first pixel value of normalized gray scale image is 100. The first value after conversion to RGB is [100, 100, 100].

Add example using HSV

import cv2
import numpy as np
image = np.random.rand(28, 28)
image = (image - image.min()) / (image.max() - image.min()) #to normalize
image = image * 120 #you can modify range of H for HSV
image = np.expand_dims(image, 2)

sv = np.zeros([28, 28, 2])
sv[:, :, 0] = 200 #you can modify value of S for HSV
sv[:, :, 1] = 100 #you can modify value of V for HSV

hsv_image = np.concatenate([image, sv], 2).astype(np.uint8)
rgb_image = cv2.cvtColor(hsv_image, cv2.COLOR_HSV2RGB)

Then you can get RGB image which has color from red to blue.

import numpy as np
import matplotlib.pyplot as plt

#"image" holds your 2D image data. np.shape(image) = 128 x 128

plt.imshow(image, interpolation='none')
plt.colorbar()
plt.show()
plt.savefig('image.pdf')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM