【问题标题】:Saving GRAYSCALE .png image with cv2.imwrite() not working使用 cv2.imwrite() 保存 GRAYSCALE .png 图像不起作用
【发布时间】:2020-07-15 17:10:37
【问题描述】:

我使用tf.keras.preprocessing.image.ImageDataGenerator 生成了图像,并绘制了使用matplotlib 生成的图像,结果如下:

这实际上是我想要保存在我的文件系统上的内容,但由于某种原因,每当我尝试使用cv2.imwrite() 函数写入图像时,我都会得到这个:

在某些情况下,保存的图像是完全空白的(所有像素都是白色的)。代码如下:

cnt = 0
for image, label in zip(augmented_images, labels):
  cnt += 1
  path = os.path.join(augmented_raw_images_train_dir,str(int(label[0])),"aug_"+str(cnt)+".png")
  cv2.imwrite(path, image[0])

请记住,图像是大小为 1 的批次,因此 image[0] 实际上是一个大小为 (150, 150, 1) 的 n-dim numpy 数组。

【问题讨论】:

    标签: python numpy opencv


    【解决方案1】:

    您数据中的像素值很可能在 [0.0, 1.0] 范围内。在通过 opencv 保存它们之前,您应该将它们转换为 [0, 255] 范围。

    cnt = 0
    for image, label in zip(augmented_images, labels):
      cnt += 1
      path = os.path.join(augmented_raw_images_train_dir,str(int(label[0])),"aug_"+str(cnt)+".png")
      image_int = np.array(255*image[0], np.uint8)
      cv2.imwrite(path, image_int)
    

    如果值在 [-1, 1] 范围内,您可以进行相应调整。

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      相关资源
      最近更新 更多