图片增强

  1. 读取图片:从img_path指定的路径读取图片。

  2. 缩小图片:使用resize_image函数将图片缩小到原来的50%。

  3. 水平翻转图片:使用flip_image函数对缩小后的图片进行水平翻转。

  4. 添加噪声:使用add_large_noise函数在翻转后的图片上添加大的黑白噪声块。

  5. 保存新的图片:将添加了噪声的翻转图片保存到output_dir指定的目录,并在文件名前添加"aug_"前缀以区分原始图片。

  6. 更新JSON文件中的file_name:读取对应的JSON文件,并更新其中的file_name字段,使其与新保存的图片文件名相匹配。

  7. 另存为新的JSON文件:将更新后的JSON数据保存为一个新的文件,文件名与原JSON文件相同但在前面添加了"aug_"前缀。

import cv2
import os
import json
import numpy as np


def add_large_noise(image):
    # 添加大的黑白噪声块
    height, width = image.shape[:2]
    num_patches = 5  # 噪声块的数量
    patch_size = 100  # 噪声块的大小
    for _ in range(num_patches):
        x = np.random.randint(0, width - patch_size)
        y = np.random.randint(0, height - patch_size)
        if np.random.rand() < 0.5:
            image[y:y + patch_size, x:x + patch_size] = 255  # 白色块
        else:
            image[y:y + patch_size, x:x + patch_size] = 0  # 黑色块
    return image


def resize_image(image, scale=0.5):
    # 缩小图片
    new_size = (int(image.shape[1] * scale), int(image.shape[0] * scale))
    return cv2.resize(image, new_size)


def flip_image(image):
    # 水平翻转图片
    return cv2.flip(image, 1)


def process_image(img_path, json_path, output_dir):
    # 读取图片
    image = cv2.imread(img_path)
    # 缩小图片
    resized_image = resize_image(image)
    # 水平翻转图片
    flipped_image = flip_image(resized_image)
    # 添加噪声
    noisy_flipped_image = add_large_noise(flipped_image)

    # 保存新的图片
    new_img_filename = f"aug_{os.path.basename(img_path)}"
    new_img_path = os.path.join(output_dir, new_img_filename)
    cv2.imwrite(new_img_path, noisy_flipped_image)

    # 更新JSON文件中的file_name
    with open(json_path, 'r') as f:
        data = json.load(f)

    # 根据您的JSON文件结构更新这里的代码
    # 例如,如果您的JSON文件中有一个'image'键,下面是如何更新它
    if 'image' in data:
        data['image']['file_name'] = os.path.splitext(new_img_filename)[0] + '.jpg'

    # 另存为新的JSON文件
    new_json_filename = f"aug_{os.path.basename(json_path)}"
    new_json_path = os.path.join(output_dir, new_json_filename)
    with open(new_json_path, 'w') as f:
        json.dump(data, f, indent=4)


def main():
    # 图片和JSON文件路径
    images_folder_path = '你的图片路径'
    jsons_folder_path = '你的json文件路径'
    output_dir = '你的生成文件路径'

    # 创建输出目录
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 遍历图片并进行数据增强
    for img_filename in os.listdir(images_folder_path):
        if img_filename.endswith(".jpg") or img_filename.endswith(".png"):
            img_path = os.path.join(images_folder_path, img_filename)
            json_filename = img_filename.replace('.jpg', '.json').replace('.png', '.json')
            json_path = os.path.join(jsons_folder_path, json_filename)
            if os.path.exists(json_path):
                process_image(img_path, json_path, output_dir)


if __name__ == '__main__':
    main()

 针对XML文件修改数据增强之后或者是转化为json文件的时候会出现扩展名的错误,修改脚本:

import json
import os

def update_json_file(json_file_path):
    # 检查文件是否存在
    if not os.path.exists(json_file_path):
        print(f"Error: The file {json_file_path} does not exist.")
        return

    # 读取JSON文件
    with open(json_file_path, 'r') as f:
        data = json.load(f)

    # 遍历所有文件名并更新扩展名
    for item in data.get('images', []):
        file_name = item.get('file_name', '')
        # 检查文件名是否有扩展名
        if not os.path.splitext(file_name)[1]:
            file_name += '.jpg'
        # 将.xml更改为.jpg
        file_name = file_name.replace('.xml', '.jpg')
        item['file_name'] = file_name

    # 保存更新后的JSON文件
    with open(json_file_path, 'w') as f:
        json.dump(data, f, indent=4)

# 指定您的JSON文件路径
json_file_path = r'D:\IBD_SoyBean\WORM\worm_10\annotations\instance_train.json'  # 使用原始字符串
update_json_file(json_file_path)

Logo

一站式 AI 云服务平台

更多推荐