python - 如何对一组图像(.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
解决方案
如果要保留原始文件名,请使用 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
推荐阅读
- c++ - 将整数转换为二进制等价物
- c# - HttpClient.PostAsync 崩溃应用。如何捕捉异常?
- flutter - 在颤动中制作一个 TextFormField 全局小部件
- javascript - 在一组卡片中仅打开一个下拉菜单
- javascript - 类似 Windows 的平铺边框效果
- javascript - 浏览器中的事件循环如何同时处理事件队列、作业队列、渲染队列?
- python - 当屏幕被阻塞时,Spyder 停止运行
- typescript - TypeError...不是一个函数
- php - Laravel Eloquent 中的 MySQL 类型 CHAR 问题
- crystal-reports - 水晶报告中有什么方法可以用法语显示总价吗