![](/img/trans.png)
[英]Check that png image and csv file has the same name before processing them
[英]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.