python - 使用cv2.imwrite()保存GREYSCALE .png图像不起作用

标签 python numpy opencv

我使用tf.keras.preprocessing.image.ImageDataGenerator生成了图像,并绘制了使用matplotlib生成的图像,结果如下:
enter image description here
这实际上是我要保存在文件系统中的内容,但是由于某种原因,每当我尝试使用cv2.imwrite()函数编写图像时,都会得到以下信息:
enter image description here
在某些情况下,保存的图像完全空白(所有像素均为白色)。这是代码:

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数组。

最佳答案

来自数据的像素值很可能在[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]范围内,则可以进行相应调整。

关于python - 使用cv2.imwrite()保存GREYSCALE .png图像不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62920233/

相关文章:

python - Django 形式不是 sh

python - 字符串切片返回意外值

python - 如何在python中将字符串转换为数字

python - 根据数组的另一列聚合一列中的最小最大值 - Python

python - 并行填充矩阵

python - 基本过滤器返回一个空列表

python - 在 Python 中使用列表理解在嵌套 for 循环中枚举

c++ - 为什么 opencv 发现轮廓的边界点是无序的和未完成的?

python - 在 Python 上使用 OpenCV 选择最佳 SVM 内核类型和参数

c - OpenCV 1.1,IplImage 无法正确显示图像