简体   繁体   English

使用 python 将 numpy 数组转换为 uint8

[英]convert numpy array to uint8 using python

My code below is intended to get a batch of images and convert them to RGB.我下面的代码旨在获取一批图像并将它们转换为 RGB。 But I keep getting an error which says to convert to type uint8.但我不断收到一个错误,说要转换为 uint8 类型。 I have seen other questions regarding the conversion to uint8, but none directly from an array to uint8.我已经看到有关转换为 uint8 的其他问题,但没有直接从数组到 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:我试图集成到我自己的代码(在另一个线程中找到,用于将类型转换为 uint8)是:

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.通常imInt是 uint8 类型,在规范化之后它是 float32 类型,因为除法导致的强制转换。 you must convert back to uint8 before saving to PNG file:在保存为 PNG 文件之前,您必须转换回 uint8:

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:请注意,这两个循环不是必需的,您可以使用 numpy 向量运算来代替:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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