网上找到的mixup只能处理图片,而没有将两图的label绘制在生成图像上。
这里贴上自己修改后能用的代码,能绘制不同颜色的框。
# -*- coding: utf-8 -*-
import cv2
import numpy as np
def draw_rectangle(image, txtfile, savefile, color):
image = cv2.imread(image)
GrayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 处理灰度图片的
with open(txtfile, 'r') as f:
lines = f.readlines()
splitlines = [x.strip().split(' ') for x in lines]
for splitline in splitlines:
if (float(splitline[1]) >= 0.5):
print(splitline)
splitline = splitline[2:]
print(splitline)
x, y, x1, y1 = splitline
x, y, x1, y1 = float(x), float(y), float(x1), float(y1)
# print(x, y, x1, y2)
draw = cv2.rectangle(image, (int(x), int(y)), (int(x1), int(y1)), color, 2)
cv2.imwrite(savefile, draw)
# 这里两图resize应相同,所以最好先将要mixup的两图先通过照片中的调整大小调整到相同的尺寸再打标签
img1 = cv2.imread('1.jpg')
img1 = cv2.resize(img1, (500, 500))
txtfile1 = "1.txt"
img2 = cv2.imread('2.jpg')
img2 = cv2.resize(img2, (500, 500))
txtfile2 = "2.txt"
alpha = 1.0
lam = np.random.beta(alpha, alpha)
mixed_img = lam * img1 + (1 - lam) * img2
cv2.imwrite('mixup.jpg', mixed_img)
# 这里调用画框函数,分两次画框
one = "mixup.jpg"
draw_1 = draw_rectangle(one, txtfile1, "one.jpg", (0, 0, 255))
# (0, 0, 255)是红色,可以根据需要更改
two = "one.jpg"
draw_2 = draw_rectangle(two, txtfile2, "two.jpg", (255, 0, 0))
其中1.txt文件如下所示,前两项其实无所谓是什么,后面四项则是框的坐标。
cat 0.99 109 29 405 457
mixup
1.jpg
D:\数据增强\mixup\1.jpg
500
500
3
0
若有多个框,按这个格式填写,不要空行。
cat 0.99 109 29 405 457
cat 0.99 210 250 369 491
结果如下。
可以看到两张图实现了mixup并且绘制了目标所在的框。
参考
https://blog.csdn.net/u013685264/article/details/122622919?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165209352016782391855338%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=165209352016782391855338&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-3-122622919-null-null.142^v9^control,157^v4^control&utm_term=mixup数据增强+python&spm=1018.2226.3001.4187https://blog.csdn.net/u013685264/article/details/122622919?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165209352016782391855338%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=165209352016782391855338&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-3-122622919-null-null.142^v9^control,157^v4^control&utm_term=mixup数据增强+python&spm=1018.2226.3001.4187https://blog.csdn.net/weixin_38145317/article/details/89497616https://blog.csdn.net/weixin_38145317/article/details/89497616