python数据增强——颜色变换(img+json)

import cv2
import os
import json


# 定义一个函数对图像进行颜色调整,两个参数用于颜色调整强度
def getColorImg(alpha, beta, img_path, img_write_path):
    img = cv2.imread(img_path)
    colored_img = cv2.convertScaleAbs(alpha + img * beta)
    cv2.imwrite(img_write_path, colored_img)


# 定义一个函数用于处理标注数据json文件
def getColorAnno(anno_path, anno_write_path):
    with open(anno_path, 'r') as json_file:
        annotation_data = json.load(json_file)  # 加载json数据
    # 对json进行修改数据
    with open(anno_write_path, 'w') as json_file:
        json.dump(annotation_data, json_file)  # 保存修改后的json文件


# 定义一个函数用于处理一组图像喝标注数据的颜色调整
def color(alpha, beta, img_dir, anno_dir, img_write_dir, anno_write_dir):
    if not os.path.exists(img_write_dir):
        os.makedirs(img_write_dir)  # 如果输出图像目录不存在就创建

    if not os.path.exists(anno_write_dir):
        os.makedirs(anno_write_dir)  # 如果输出标注目录不存在就创建

    img_names = os.listdir(img_dir)  # 获取输入图像目录中的图像文件列表
    for img_name in img_names:
        img_path = os.path.join(img_dir, img_name)  # 构建输入图像文件路径
        img_write_path = os.path.join(img_write_dir, img_name[:-4] + '-'+ str(int(alpha * 10)) + '.jpg')

        anno_path = os.path.join(anno_dir, img_name[:-4] + '.json')
        anno_write_path = os.path.join(anno_write_dir, img_name[:-4] + '-' + str(int(alpha * 10)) + '.json')

        getColorImg(alpha, beta, img_path, img_write_path)  # 对图像进行颜色调整
        getColorAnno(anno_path, anno_write_path)  # 对标注文件进行调整


alphas = [0.3, 0.5, 1.2, 1.6]
beta = 10
img_dir = 'JPEGImages'
anno_dir = 'Annotations'
img_write_dir = 'Color/color_JPEGImages'
anno_write_dir = 'Color/color_Annotations'

for alpha in alphas:
    color(alpha, beta, img_dir, anno_dir, img_write_dir, anno_write_dir)

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值