[Python programming] Convert the npy image to png format, and then save it to another folder, and the saved file name is the same as the original

import the necessary libraries

import numpy as np
import matplotlib.pyplot as plt
import os
import scipy.misc
import imageio   # 用于保存灰度图

Input and output path variable definition

input_dir = r"D:\PApple_RGB-D-Size_dataset_v1\depthCropNpy"

output_dir = r"D:\out"
    if not os.path.exists(output_dir):      # 如果路径不存在,则对其进行创建
        os.makedirs(output_dir)

output_dir1 = r"D:\out1"
if not os.path.exists(output_dir1):
        os.makedirs(output_dir1)

loop through

files = os.listdir(input_dir)    # 获取输入路径文件夹下的文件 
for i in files:
    
    depthmap = np.load(path1+"/" + i)    # 加载读取图片
    
    filename = str(i)    # 将循环变量转换为字符串,以便后面文件名的保留命名
    new_filename = os.path.splitext(filename)[0] + '.png'   # 新文件名变量的定义
    
    save_path = os.path.join(output_dir, new_filename)  # 将新文件名与输出路径进行连接
    plt.imsave(save_path,depthmap)   # 将转换后的文件保存在输出路径下

    save_path1 = os.path.join(output_dir1,new_filename)
    imageio.imsave(save_path1,depthmap)   # 将转换后的图片以灰度图保存在输出路径下

The above is the case of saving with the original file name, and the following describes the case of saving with serial number.

code show as below:

import numpy as np
import matplotlib.pyplot as plt
import os
import scipy.misc
import imageio

path1 = r"D:\PApple_RGB-D-Size_dataset_v1\depthCropNpy"
files = os.listdir(path1)
n=1

for i in files:
    depthmap = np.load(path1+"/" + i)
    plt.imsave(r"D:\out\no " + str(n) + ".png",depthmap)
    imageio.imsave(r"D:\out1\no " + str(n) + ".png",depthmap)
    n = n+1

Full code:

import numpy as np
import matplotlib.pyplot as plt
import os
import scipy.misc
import imageio   # 用于保存灰度图

input_dir = r"D:\PApple_RGB-D-Size_dataset_v1\depthCropNpy"

output_dir = r"D:\out"
    if not os.path.exists(output_dir):      # 如果路径不存在,则对其进行创建
        os.makedirs(output_dir)

output_dir1 = r"D:\out1"
if not os.path.exists(output_dir1):
        os.makedirs(output_dir1)

files = os.listdir(input_dir)    # 获取输入路径文件夹下的文件 
for i in files:
    
    depthmap = np.load(path1+"/" + i)    # 加载读取图片
    
    filename = str(i)    # 将循环变量转换为字符串,以便后面文件名的保留命名
    new_filename = os.path.splitext(filename)[0] + '.png'   # 新文件名变量的定义
    
    save_path = os.path.join(output_dir, new_filename)  # 将新文件名与输出路径进行连接
    plt.imsave(save_path,depthmap)   # 将转换后的文件保存在输出路径下

    save_path1 = os.path.join(output_dir1,new_filename)
    imageio.imsave(save_path1,depthmap)   # 将转换后的图片以灰度图保存在输出路径下

Guess you like

Origin blog.csdn.net/lingchen1906/article/details/131426255