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

问题描述

我有 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

标签: pythonimage-processingsemantic-segmentation

解决方案


如果要保留原始文件名,请使用 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

推荐阅读