我正在尝试递归地将img
文件夹中的所有文件转换为灰度,并将结果保存在imgGray
文件夹中
但在我的目标文件夹中:
我只得到从每个子目录(A,B ...
)转换的第一个图像,下面是树的样子:
__img__A____A1.jpg
| | |__A2.jpg
| | .
| | .
| | .__An.jpg
| |
| |___B__B1.jpg
| | |__B2.jpg
| | .
| | .
| | .__Bn.jpg
|
|__imgGray__A__A1.jpg
|
|
|______B__B1.jpg
我不确定是否正确使用了glob.glob(os.path.join(x[0],"*.jpg"))
函数?或者代码的哪一部分是错误的
以下是我为该任务准备的代码:
import cv2
import os,glob,re
from os import listdir,makedirs
from os.path import isfile,join
pwd = os.getcwd()
path = os.path.join(pwd,'img') # Source Folder
dstpath = os.path.join(pwd,'imgGray') # Destination Folder
for x in os.walk(path):
y = x[0][len(path):]
subFolderDest = dstpath+y
try:
os.mkdir(subFolderDest)
except:
print ("Directory already exist, images will be written in same subfolder:"+subFolderDest)
variable = input('continue? y/n: ')
if variable == 'n':
exit(0)
# Folder won't used
files = [f for f in listdir(x[0]) if isfile(join(x[0],f))]
print(x[0]+str(len(files)))
for image in files:
try:
img = cv2.imread(os.path.join(x[0],image))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
subFolderDest = join(subFolderDest,image)
cv2.imwrite(subFolderDest,gray)
except:
print ("{} is not converted".format(image))
for fil in glob.glob(os.path.join(x[0],"*.jpg")):
try:
image = cv2.imread(fil)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to greyscale
cv2.imwrite(os.path.join(subFolderDest,fil),gray_image)
except:
print('{} is not converted')
这个用于遍历目录树的简化逻辑应该可以做到这一点
我已经省略了实际的转换函数,您的代码应该适用于它
从
/something
运行此命令,它会打印出来通过编辑整个解决方案,我成功地获得了以下代码:
相关问题 更多 >
编程相关推荐