yolov5翻转数据增强

这段代码涉及图像处理,包括读取图片、旋转图片,并对标注文件进行处理。它遍历指定目录下的图像文件,读取对应的标注信息,进行坐标转换,并保存旋转后的标注文件和图像。同时,代码还展示了如何在图像上绘制矩形框,用于视觉验证标注。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import cv2
from PIL import Image
import numpy as np
import os

for file in os.listdir('/home/lixuan/Downloads/payactions/scanandpay/images/train'):
    imgpath = '/home/lixuan/Downloads/payactions/scanandpay/images/train/{}'.format(file)
    txtpath = '/home/lixuan/Downloads/payactions/scanandpay/labels/train/{}'.format(file.replace('jpg','txt'))

    img = cv2.imread(imgpath)
    f = open(txtpath)
    datas = f.readlines()
    f.close()
    fw = open('/home/lixuan/Downloads/payactions/scanandpay/rotatelabel/rotate_{}'.format(file.replace('jpg','txt')),'w')
    for data in datas:
        data = data.strip().split(' ')
        lab = data[0]
        data = data[1:]
        data = [float(d) for d in data]
        data[0] *= img.shape[1]
        data[1] *= img.shape[0]
        data[2] *= img.shape[1]
        data[3] *= img.shape[0]
        x = img.shape[1] - data[0]
        y = img.shape[0] - data[1]
        w = data[2]
        h = data[3]
        fw.write(lab + ' ' + str(x / img.shape[1]) + ' ' + str(y / img.shape[0]) + ' ' + str(w / img.shape[1]) + ' ' + str(h / img.shape[0]) + '\n')
    fw.close()
    img = Image.fromarray(img)
    img = img.transpose(Image.ROTATE_180)
    img.save('/home/lixuan/Downloads/payactions/scanandpay/roteteimg/rotate_{}'.format(file))
import cv2
from PIL import Image
import numpy as np
import os

for file in os.listdir('/home/lixuan/fromLX/coco/images/train'):
    imgpath = '/home/lixuan/fromLX/coco/images/train/{}'.format(file)
    txtpath = '/home/lixuan/fromLX/coco/labels/train/{}'.format(file.replace('jpg', 'txt').replace('JPG', 'txt').replace('jpeg', 'txt'))

    img = cv2.imread(imgpath)
    DS = open(txtpath)
    datas = DS.readlines()
    for data in datas:
        data = data.strip().split(' ')
        data = [float(x) for x in data]
        label = str(int(data[0]))

        data[1] *= img.shape[1]
        data[2] *= img.shape[0]
        data[3] *= img.shape[1]
        data[4] *= img.shape[0]
        x = data[1]
        y = data[2]
        w = data[3]
        h = data[4]
        x1 = int(x - w / 2)
        y1 = int(y - h / 2)
        x2 = int(x1 + w)
        y2 = int(y1 + h)
        if label == '0':
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 5)
        else:
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 5)
    cv2.imwrite('/home/lixuan/fromLX/coco/show/{}'.format(file),img)
    # cv2.namedWindow('img', 0)
    # cv2.imshow('img', img)
    # cv2.waitKey(0)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值