参考:https://www.jianshu.com/p/433bfe17df08
import os
from PIL import Image
#采用递归遍历的方式遍历图片
def recurve_opt(root_1, root_2):
if not os.path.exists(root_2):
os.makedirs(root_2)
for file in os.listdir(root_1):
source_file = os.path.join(root_1, file)
target_file = os.path.join(root_2, file)
if os.path.isfile(source_file):
(path, extension) = os.path.splitext(source_file)
if extension == '.png':
source_img=Image.open(source_file)
if "ground_truth" in path:
gray_img=source_img
else:
gray_img=source_img.convert("L")
gray_img.save(target_file)
else:
recurve_opt(source_file, target_file)
def main():
imgRoot="MyData"
imgRootGray="MyDataGray"
recurve_opt(imgRoot, imgRootGray)
if __name__ == '__main__':
main()
import os
import cv2
#采用递归遍历的方式遍历图片
def recurve_opt(root_1, root_2):
if not os.path.exists(root_2):
os.makedirs(root_2)
for file in os.listdir(root_1):
source_file = os.path.join(root_1, file)
target_file = os.path.join(root_2, file)
if os.path.isfile(source_file):
(path, extension) = os.path.splitext(source_file)
if extension == '.png':
source_img=cv2.imread(source_file)
source_img=cv2.resize(source_img,(512,512),interpolation=cv2.INTER_CUBIC)
gray_img=cv2.cvtColor(source_img,cv2.COLOR_RGB2GRAY)
cv2.imwrite(target_file,gray_img)
else:
recurve_opt(source_file, target_file)
def main():
imgRoot="MyData"
imgRootGray="MyDataGray"
recurve_opt(imgRoot, imgRootGray)
if __name__ == '__main__':
main()
注意,以上代码尽管形式上改为了单通道图像,但是读入的时候可能还会受读入函数的影响,例如opencv的imread默认就是以3通道图像读入,这时候需要指定imread(...,-1)这个参数才是以单通道的形式读入。