递归地将图像文件转换到另一个目标文件夹

2024-09-30 16:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试递归地将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')

Tags: pathinimageimport文件夹imgforos
2条回答

这个用于遍历目录树的简化逻辑应该可以做到这一点

我已经省略了实际的转换函数,您的代码应该适用于它

import os

def convert_image(source_path, dest_path):
    print(f'Would convert {source_path} -> {dest_path}')

pwd = os.getcwd()
source_dir = os.path.join(pwd, 'img')
dest_dir = os.path.join(pwd, 'imgGray')

for dirpath, dirnames, filenames in os.walk(source_dir):
    for filename in filenames:
        if filename.endswith('.png'):
            source_path = os.path.join(dirpath, filename)
            dest_path = os.path.join(dest_dir, os.path.relpath(dirpath, source_dir), filename)
            os.makedirs(os.path.dirname(dest_path), exist_ok=True)
            convert_image(source_path, dest_path)

/something运行此命令,它会打印出来

Would convert /something/img/a/4.png -> /something/imgGray/a/4.png
Would convert /something/img/a/1.png -> /something/imgGray/a/1.png
Would convert /something/img/c/6.png -> /something/imgGray/c/6.png
Would convert /something/img/c/3.png -> /something/imgGray/c/3.png
Would convert /something/img/b/5.png -> /something/imgGray/b/5.png
Would convert /something/img/b/2.png -> /something/imgGray/b/2.png

通过编辑整个解决方案,我成功地获得了以下代码:

import cv2
import os,glob,re
from PIL import Image
from os import listdir,makedirs
from os.path import isfile,join    

def convert_image(source_path, dest_path):
    image = cv2.imread(source_path)
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)    
    cv2.imwrite(dest_path, image_gray)
    print(f'Would convert {source_path} -> {dest_path}')

pwd = os.getcwd()
source_dir = os.path.join(pwd, 'img') # Source Folder
dest_dir = os.path.join(pwd, 'imgGray') # Destination Folder

for dirpath, dirnames, filenames in os.walk(source_dir):
    for filename in filenames:
        if filename.endswith('.jpg'):
            source_path = os.path.join(dirpath, filename)
            dest_path = os.path.join(dest_dir, os.path.relpath(dirpath, source_dir), filename)
            os.makedirs(os.path.dirname(dest_path), exist_ok=True)
            convert_image(source_path, dest_path)

相关问题 更多 >