Stefan Radonjic
Stefan Radonjic

Reputation: 1598

Saving GRAYSCALE .png image with cv2.imwrite() not working

I've generated images by using tf.keras.preprocessing.image.ImageDataGenerator and I've plotted what I've generated using matplotlib, here are the results:

enter image description here

This is actually what I want saved on my file system, but for some reason whenever I try to write the image using cv2.imwrite() function I get this:

enter image description here

In some cases the image that is saved is completely blank (all pixels are white). Here is the code:

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])

Have in mind that image is a batch of size 1, so image[0] is actually a n-dim numpy array of size (150, 150, 1).

Upvotes: 1

Views: 3409

Answers (1)

unlut
unlut

Reputation: 3775

Most likely your pixel values from your data is in range [0.0, 1.0]. You should convert them to [0, 255] range before saving them via opencv.

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)

If values are in [-1, 1] range you can adjust accordingly.

Upvotes: 4

Related Questions