如何对一组图像(.png 格式)执行二进制阈值处理并将它们写入具有相同文件名(和相同的 .png 扩展名)的另一个文件夹中?

How to perform binary thresholding on a set of images (.png format) and write them in another folder with same file name (and same .png extension)?

我有 450 个 .png 格式的图像标签(用于语义分割)。但是,为了使用这些图像,我必须将它们转换为二进制图像。因此,我编写了执行此任务的代码。但是,在保存这些二进制图像的最终文件夹中,文件名被打乱了。我不明白为什么。下面是我的代码。

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

如果您想保留原始文件名,请使用 basename 函数:

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