簡體   English   中英

如何對一組圖像(.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM