简体   繁体   中英

convert numpy array to uint8 using python

My code below is intended to get a batch of images and convert them to RGB. But I keep getting an error which says to convert to type uint8. I have seen other questions regarding the conversion to uint8, but none directly from an array to uint8. Any advice on how to make that happen is welcome, thank you!

from skimage import io
import numpy as np
import glob, os
from tkinter import Tk
from tkinter.filedialog import askdirectory
import cv2

# wavelength in microns
MWIR = 4.5
R = .692
G = .582
B = .140

rgb_sum = R + G + B;
NRed = R/rgb_sum;
NGreen = G/rgb_sum;
NBlue = B/rgb_sum;

path = askdirectory(title='Select PNG Folder') # shows dialog box and return the path
outpath = askdirectory(title='Select SAVE Folder') 
for file in os.listdir(path):
    if file.endswith(".png"):
        imIn = io.imread(os.path.join(path, file))
        imOut = np.zeros(imIn.shape)    

        for i in range(imIn.shape[0]): # Assuming Rayleigh-Jeans law
            for j in range(imIn.shape[1]):
                imOut[i,j,0] = imIn[i,j,0]/((NRed/MWIR)**4)
                imOut[i,j,1] = imIn[i,j,0]/((NGreen/MWIR)**4)
                imOut[i,j,2] = imIn[i,j,0]/((NBlue/MWIR)**4)
        io.imsave(os.path.join(outpath, file) + '_RGB.png', imOut)

the code I am trying to integrate into my own (found in another thread, used to convert type to uint8) is:

info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

thank you!

Normally imInt is of type uint8, after your normalisation it is of type float32 because of the casting cause by the division. you must convert back to uint8 before saving to PNG file:

io.imsave(os.path.join(outpath, file) + '_RGB.png', imOut.astype(np.uint8))

Note that the two loops are not necessary, you can use numpy vector operations instead:

MWIR = 4.5

R = .692
G = .582
B = .140

vector = [R, G, B]
vector = vector / vector.sum()
vector = vector / MWIR
vector = np.pow(vector, 4)

for file in os.listdir(path):
  if file.endswith((".png"):
    imgIn = ...
    imgOut = imgIn * vector
    io.imsave(
      os.path.join(outpath, file) + '_RGB.png', 
      imgOut.astype(np.uint8))

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