1.原图和JSON转黑红图
import os
json_folder = r"D:\labelme\csimg"
FileNameList = os.listdir(json_folder)
os.system("conda activate labelme")
output_folder = os.path.join(json_folder, "../data")
os.makedirs(output_folder, exist_ok=True)
for i in range(len(FileNameList)):
if (os.path.splitext(FileNameList[i])[1] == ".json"):
json_file = os.path.join(json_folder, FileNameList[i])
output_file = os.path.join(output_folder, os.path.splitext(FileNameList[i])[0] + ".png")
os.system("labelme_json_to_dataset " + json_file + " -o " + output_file)
2.重命名黑红图与原图保持一致并输出到文件夹下
import os
import shutil
source_folder = r'D:\labelme\csimg\data'
destination_folder = r'D:\labelme\csimg\data2\Black_red'
for root, dirs, files in os.walk(source_folder):
for file in files:
if file == 'label.png':
folder_name = os.path.basename(root).replace('_json', '')
new_file_name = folder_name + '.png'
source_path = os.path.join(root, file)
destination_path = os.path.join(destination_folder, new_file_name)
shutil.move(source_path, destination_path)
3.原图批量转移到文件夹下
import os
import shutil
source_folder = r'D:\labelme\csimg\data'
destination_folder = r'D:\labelme\csimg\data2\img'
for root, dirs, files in os.walk(source_folder):
for file in files:
if file == 'img.png':
folder_name = os.path.basename(root).replace('_json', '')
new_file_name = folder_name + '.png'
source_path = os.path.join(root, file)
destination_path = os.path.join(destination_folder, new_file_name)
shutil.move(source_path, destination_path)
4.黑红图批量变黑白图
import numpy as np
import os
from PIL import Image
np.set_printoptions(threshold=np.inf)
def RedToWhite(img_dir, new_img_dir):
folders = os.listdir(img_dir)
for floder in folders:
image_path = os.path.join(img_dir, floder)
img = Image.open(image_path)
newImg = np.array(img) * 255
newImg = newImg.astype(np.uint8)
newImg = Image.fromarray(newImg)
newImg_path = os.path.join(new_img_dir, floder)
newImg.save(newImg_path)
if __name__ == '__main__':
img_path = r'D:\labelme\csimg\data2\Black_red'
newImg_path = r'D:\labelme\csimg\data2\Black_white'
RedToWhite(img_path, newImg_path)