0

I have 450 image labels (for semantic segmentation) in .png format. But, in order to use these images, I have to convert them into binary images. So, I have written a code which performs this task. However, in the final folder where these binary images are saved, the file names got shuffled. I am unable to understand why. Below is my code.

import matplotlib, cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageOps
import glob

%matplotlib inline

filename = '/content/gdrive/My Drive/mm/train_labels_binary/'  #folder to save output images
images = glob.glob("/content/gdrive/My Drive/mm/train_labels/*.png")
print(len(images))

image_no = 1

for image in images:
  img = cv2.imread(image)
  gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
  _,threshold_img = cv2.threshold(gray_img, 181, 255, cv2.THRESH_BINARY)
  #threshold_img = cv2.cvtColor(threshold_img, cv2.COLOR_GRAY2RGB)
  cv2.imwrite(filename + str(image_no) + '.png', threshold_img) 
  image_no = image_no + 1

1 Answers1

0

If you want to preserve the original filenames use the basename function:

import os

filename = '/content/gdrive/My Drive/mm/train_labels_binary/'  #folder to save output images
images = glob.glob("/content/gdrive/My Drive/mm/train_labels/*.png")
print(len(images))

image_no = 1

for image in images:
  img = cv2.imread(image)
  gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
  _,threshold_img = cv2.threshold(gray_img, 181, 255, cv2.THRESH_BINARY)
  #threshold_img = cv2.cvtColor(threshold_img, cv2.COLOR_GRAY2RGB)
  image_filename = os.path.basename(image)
  path = os.path.join(filename, image_filename)
  cv2.imwrite(path, threshold_img) 
  image_no = image_no + 1
2ps
  • 15,099
  • 2
  • 27
  • 47