Note | Python

1. list方法

  • index():只返回第一个查询到的的索引值。
    如果要返回多个,建议用列表推导和max()方法,逐个对比即可。

2. os

  • 查看目录是否存在,不存在则创建

    if not os.path.exists(dir_save_stack):
        os.makedirs(dir_save_stack) # 如果是单层目录,可以用mkdir

3. imageio

  • 保存灰度图像数组为png
    假设Y通道经过处理后,得到了一个[0,1]之间类型为np.float32的数组output。我们想保存到output_path路径,步骤为:去掉多余的B和C维度 => 脱离梯度运算,转移至CPU,转换为numpy数组 => 乘以255 => 转换为uint8格式 => imageio.imwrite保存。

    imageio.imwrite(output_path, ((torch.squeeze(output).detach().cpu().numpy()) * 255).astype(np.uint8))

警告:我曾经尝试过保存为png,结果图像被有损压缩了。如果需要进一步处理(比如算psnr),建议保存为bmp。

4. Python Image Libarary (PIL)

  • JPEG压缩并保存

    from PIL import Image
    img = Image.open("lena.png")
    img.save(img_save_path, "JPEG", quality=quality) # quality = 1 is the worst, quality = 95 is the best

5. random

  • 按种子打乱序列

    random.seed(17)
    random.shuffle(order)

6. time

  • time.time():返回以秒为单位的、从1970年1月1日午夜(历元)经过的时间。

猜你喜欢

转载自www.cnblogs.com/RyanXing/p/Python.html