使用python将numpy数组转换为uint8

2024-09-26 18:03:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我下面的代码旨在获取一批图像并将其转换为RGB。但我一直收到一个错误,它说转换为uint8类型。我已经看到了关于转换到uint8的其他问题,但是没有直接从数组转换到uint8的问题。欢迎就如何实现这一目标提供任何建议,谢谢

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)

我试图集成到自己的代码中(在另一个线程中找到,用于将类型转换为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)

谢谢大家!


Tags: thepathinfromimportdataosnp
1条回答
网友
1楼 · 发布于 2024-09-26 18:03:07

通常imInt是uint8类型,在归一化之后,它是float32类型,这是因为分割导致的强制转换。保存到PNG文件之前,必须转换回uint8:

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

请注意,这两个循环不是必需的,您可以改为使用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))

相关问题 更多 >

    热门问题