如何訓(xùn)練帶旋轉(zhuǎn)參數(shù)的 YOLOV5 模型
代碼倉庫
git clone https://github.com/hukaixuan19970627/yolov5_obb.git
數(shù)據(jù)集準(zhǔn)備
數(shù)據(jù)標(biāo)注
rolabelimg 安裝
參考: rolabelimg
windows 下虛擬環(huán)境進(jìn)行操作
git clone https://github.com/cgvict/roLabelImg.git
cd rolabelimg
pyrcc5 -o resources.py resources.qrc
** 運(yùn)行 **
python rolabelimg.py
標(biāo)注快捷鍵
w : 創(chuàng)建矩形框
e : 創(chuàng)建帶旋轉(zhuǎn)的矩形框
z篓吁,x, c, v : 【大/小】幅度進(jìn)行【順時(shí)針/逆時(shí)針】旋轉(zhuǎn)
a : 上一張
d : 下一張
ctrl + s : 保存(重要)
數(shù)據(jù)預(yù)處理
import os
import xml.etree.ElementTree as ET
import cv2
import random
from tqdm import tqdm
from multiprocessing import Pool
import numpy as np
random.seed(0)
import shutil
import math
pi = math.pi
img_path = r"./ADD/albums/images/"
anno_path = r"./ADD/albums/Annotations/"
label_path = r"./ADD/albums/labelTxt/"
# with open("jsxs_data.txt","w") as F:
classes = ['daozha']
# classes = ['sly_dmyw', 'yw_gkxfw', 'yw_nc', 'gbps', 'xmbhyc', 'xmbhzc', 'kgg_ybh', 'kgg_ybf', 'wcaqm', 'aqmzc', 'wcgz', 'gzzc',
# 'xy', 'jyz_pl','byq_hxq', 'hxq_gjbs', 'hxq_gjzc', 'hxq_gjtps', 'ywzt_yfyc', 'bj_bpmh', 'bj_bpps', 'bj_wkps', 'bjdsyc', 'bjzc', 'bj',
# 'bj_sxb','sxb_bjdsyc','sxb_bjdszc']
# with open("jsxs_data.txt","w") as F:
root_path = './'
ftrain = open(root_path+'trainb.txt', 'w')
ftest = open(root_path+'testb.txt', 'w')
train_percent = 0.8
files = os.listdir(anno_path)
num = len(files)
print('num image',num)
list = range(num)
tr = int(num * train_percent)
train_list = random.sample(list, tr)
print('len train',train_list)
if not os.path.exists(label_path):
os.makedirs(label_path)
def resi(num):
x = round(num, 6)
x = str(abs(x))
while len(x) < 8:
x = x + str(0)
return x
def convert(size, box):
dw = 1./size[0]
dh = 1./size[1]
x = (box[0] + box[1])/2.0 # x = x軸中點(diǎn)
y = (box[2] + box[3])/2.0 # y = y軸中點(diǎn)
w = box[1] - box[0] #w = width
h = box[3] - box[2] # h = height
x = resi(x*dw)
w = resi(w*dw)
y = resi(y*dh)
h = resi(h*dh)
return (x,y,w,h)
def convert2(cx,cy,w,h,a,xmax,ymax):
if a>=pi:
a-=pi
#計(jì)算斜徑半長(zhǎng)
l=math.sqrt(w**2+h**2)/2
#計(jì)算初始矩形角度
a0=math.atan(h/w)
#旋轉(zhuǎn),計(jì)算旋轉(zhuǎn)角
#右上角點(diǎn) ↗
a1=a0+a
x1=int(cx+l*math.cos(a1)) if int(cx+l*math.cos(a1))<xmax else xmax
y1=int(cy+l*math.sin(a1)) if int(cy+l*math.sin(a1))<ymax else ymax
#右下角點(diǎn) ↘
a2=-a0+a
x2=int(cx+l*math.cos(a2)) if int(cx+l*math.cos(a2))<xmax else xmax
y2=int(cy+l*math.sin(a2)) if int(cy+l*math.sin(a2))<ymax else ymax
#左下角點(diǎn) ↙
a3=a1+pi
x3=int(cx+l*math.cos(a3)) if int(cx+l*math.cos(a3))<xmax else xmax
y3=int(cy+l*math.sin(a3)) if int(cy+l*math.sin(a3))<ymax else ymax
#左上角點(diǎn) ↖
a4=a2+pi
x4=int(cx+l*math.cos(a4)) if int(cx+l*math.cos(a4))<xmax else xmax
y4=int(cy+l*math.sin(a4)) if int(cy+l*math.sin(a4))<ymax else ymax
return [x1,y1,x2,y2,x3,y3,x4,y4,classes[0],0]
import glob
def process(anno_path,name):
global train_list
found_flag = 0
img_names = ['.jpg','.JPG','.PNG','.png']
for j in img_names:
img_name = os.path.splitext(name)[0] + j
if os.path.exists(img_path + img_name):
break
xml_name = os.path.splitext(name)[0] + ".xml"
txt_name = os.path.splitext(name)[0] + ".txt"
string1 = ""
# print(name)
w,h = None, None
xml_file = ET.parse(anno_path + xml_name)
root = xml_file.getroot()
try:
with open(img_path + img_name, 'rb') as f:
check = f.read()[-2:]
if check != b'\xff\xd9':
print('JPEG File collapse:', img_path + img_name)
a = cv2.imdecode(np.fromfile(img_path + img_name,dtype=np.uint8),-1)
cv2.imencode(".jpg", a)[1].tofile(img_path + img_name)
height,width = cv2.imdecode(np.fromfile(img_path +
img_name,dtype=np.uint8),-1).shape[:2]
print('----------Rewrite & Read image successfully----------')
else:
height,width = cv2.imdecode(np.fromfile(img_path + img_name,dtype=np.uint8),-1).shape[:2]
except:
print(img_path + img_name)
if (width is not None) and (height is not None):
count = 0
for child in root.findall('object'):
if child != '':
count = count + 1
if count != 0:
string1 = []
for obj in root.iter('object'):
cls = obj.find('name').text
if cls in classes:
cls_id = classes.index(cls)
else:
print(cls)
continue
xmlbox = obj.find('robndbox')
b = (float(xmlbox.find('cx').text), float(xmlbox.find('cy').text), float(xmlbox.find('w').text),
float(xmlbox.find('h').text),float(xmlbox.find('angle').text))
cx,cy,w,h,a = b
bb = convert2(cx,cy,w,h,a,width,height)
#[x1,y1,x2,y2,x3,y3,x4,y4,"daozha",0]
# for a in bb:
# if float(a) > 1.0:
# print(anno_path + xml_name + "wrong xywh",bb)
# return
string1.append( " ".join([str(a) for a in bb]) + '\n')
out_file = open(label_path + txt_name, "w")
for string in string1:
out_file.write(string)
out_file.close()
else:
print('count=0')
print(img_name,"write no label txt file")
out_file = open(label_path + txt_name, "w")
else:
print('wh is none')
def main():
pbar = tqdm(total=(len(files)))
update = lambda *args: pbar.update()
pool = Pool(6)
for i, name in enumerate(files):
pool.apply_async(process, args=(anno_path,name), callback=update)
# pbar.update(1)
pool.close()
pool.join()
img_names = ['.jpg','.JPG','.PNG','.png']
for i, name in enumerate(files):
for j in img_names:
img_name = os.path.splitext(name)[0] + j
if os.path.exists(img_path + img_name):
break
if i in train_list:
ftrain.write(img_path + img_name + "\n")
else:
ftest.write(img_path + img_name + "\n")
# 如果有只有圖片沒有xml的铭污,需要生成空白txt
# imgs = os.listdir(img_path)
# for img_name in imgs:
# txt_name = os.path.basename(img_name).split('.')[0] + '.txt'
# if not os.path.exists(label_path+txt_name):
# a = open(label_path+txt_name,'w')
# ftrain.write(img_path+img_name + "\n")
if __name__ == '__main__':
main()
格式和 yolov5_v6.1 差不多
準(zhǔn)備如下,注意 labelTxt 名字
./yq_xz_left_right:
├── Annotations
│ ├── 1.xml
│ └── 2.xml
├── images
│ ├── 1.jpg
│ └── 2.jpg
├── labelTxt
│ ├── 1.txt
│ └── 2.txt
├── test.txt
└── train.txt
開始訓(xùn)練
訓(xùn)練準(zhǔn)備
git clone https://github.com/hukaixuan19970627/yolov5_obb.git
cd yolov5_obb
修改 data/demo.yaml 里面的 train test 的 txt路徑
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ./dataset # dataset root dir
train: yq_xz_left_right/train.txt # train images (relative to 'path')
val: yq_xz_left_right/test.txt # val images (relative to 'path')
test: yq_xz_left_right/test.txt # test images (optional)
# Classes
nc: 2 # number of classes
names: ['daozha','truck'] # class names
注意類別至少2類讥蟆,修改 data/hyp/xxx.yaml 學(xué)習(xí)率等參數(shù)
訓(xùn)練命令和測(cè)試命令
python -m torch.distributed.launch --nproc_per_node 3 train.py --device 1,2,3 --weights '' --cfg models_obb/yolov5x.yaml --data data/daozha2.yaml --hyp runs/train/daozhaX_lr00552/hyp.yaml --epochs 350 --batch-size 33 --imgsz 640 --name fuyuan --sync-bn
python detect.py --weights xxx --source xxx
一鍵順控模板準(zhǔn)備
# YOLOv5 ?? by Ultralytics, GPL-3.0 license
"""
Run inference on images, videos, directories, streams, etc.
Usage:
$ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam
img.jpg # image
vid.mp4 # video
path/ # directory
path/*.jpg # glob
'https://youtu.be/Zgi9g1ksQHc' # YouTube
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
"""
import argparse
import os
import sys
from pathlib import Path
import cv2
import torch
import torch.backends.cudnn as cudnn
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from models.common import DetectMultiBackend
from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr,
increment_path, non_max_suppression, non_max_suppression_obb, print_args, scale_coords, scale_polys, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync
from utils.rboxs_utils import poly2rbox, rbox2poly
def DeleteSmallBox(det):
boxes = det.cpu().numpy()
"""
in: 檢出超過3個(gè)框的det
out: 最大的2個(gè)框
"""
areas = list()
RBoxes = list()
for box in boxes:
w,h = box[2],box[3]
areas.append(w*h)
print('AREAS >>',areas)
for i in range(2):
print('RBOXES >>',RBoxes)
RBoxes.append(boxes[areas.index(max(areas))])
areas.pop(areas.index(max(areas)))
W1 = RBoxes[0][2]
W2 = RBoxes[1][2]
if W1>W2:
RBoxes[0],RBoxes[1] = RBoxes[1],RBoxes[0]
return RBoxes
@torch.no_grad()
def run(weights=ROOT / 'yolov5s.pt', # model.pt path(s)
source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
imgsz=(640, 640), # inference size (height, width)
conf_thres=0.25, # confidence threshold
iou_thres=0.15, # NMS IOU threshold
max_det=1000, # maximum detections per image
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
view_img=False, # show results
save_txt=False, # save results to *.txt
save_conf=False, # save confidences in --save-txt labels
save_crop=False, # save cropped prediction boxes
nosave=False, # do not save images/videos
classes=None, # filter by class: --class 0, or --class 0 2 3
agnostic_nms=False, # class-agnostic NMS
augment=False, # augmented inference
visualize=False, # visualize features
update=False, # update all models
project=ROOT / 'runs/detect', # save results to project/name
name='exp', # save results to project/name
exist_ok=False, # existing project/name ok, do not increment
line_thickness=3, # bounding box thickness (pixels)
hide_labels=False, # hide labels
hide_conf=False, # hide confidences
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
):
source = str(source)
save_img = not nosave and not source.endswith('.txt') # save inference images
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
if is_url and is_file:
source = check_file(source) # download
# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Load model
device = select_device(device)
model = DetectMultiBackend(weights, device=device, dnn=dnn)
stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
imgsz = check_img_size(imgsz, s=stride) # check image size
# Half
half &= (pt or jit or engine) and device.type != 'cpu' # half precision only supported by PyTorch on CUDA
if pt or jit:
model.model.half() if half else model.model.float()
# Dataloader
if webcam:
view_img = check_imshow()
cudnn.benchmark = True # set True to speed up constant image size inference
# source = '/ssd/yangyuqian/projects/yolov5_obb-master/dataset/mp4/h/0026_normal.mp4'
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
bs = len(dataset) # batch_size
else:
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
bs = 1 # batch_size
vid_path, vid_writer = [None] * bs, [None] * bs
# Run inference
model.warmup(imgsz=(1, 3, *imgsz), half=half) # warmup
dt, seen = [0.0, 0.0, 0.0], 0
for path, im, im0s, vid_cap, s in dataset:
txt_name = path.replace('.mp4','.txt')
t1 = time_sync()
im = torch.from_numpy(im).to(device)
im = im.half() if half else im.float() # uint8 to fp16/32
im /= 255 # 0 - 255 to 0.0 - 1.0
if len(im.shape) == 3:
im = im[None] # expand for batch dim
t2 = time_sync()
dt[0] += t2 - t1
# Inference
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
pred = model(im, augment=augment, visualize=visualize)
t3 = time_sync()
dt[1] += t3 - t2
# NMS
# pred: list*(n, [cxcylsθ, conf, cls]) θ ∈ [-pi/2, pi/2)
pred = non_max_suppression_obb(pred, conf_thres, iou_thres, classes, agnostic_nms, multi_label=True, max_det=max_det)
dt[2] += time_sync() - t3
# Second-stage classifier (optional)
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
# Process predictions
need_check = False
for i, det in enumerate(pred): # per image
# print(len(det),len(pred))
if len(det)>2:
res = DeleteSmallBox(det) # 取其中的兩個(gè)大框
need_check = True
print(path)
elif len(det)<=1:
print("number of isolator is less than 2!>>")
continue
else:
res = det.cpu().numpy().tolist()
W1 = res[0][0]
W2 = res[1][0]
if W1>W2:
print("調(diào)換位置")
res2 = [res[1],res[0]]
res = res2
# print(det,'\n',res)
with open(txt_name,'a+') as f:
# if need_check:
# # print('檢查',path,W1,W2)
# need_check = False
f.write('%s,%s >>>%s\n' %(res[0][4],res[1][4],str(i)))
# continue
pred_poly = rbox2poly(det[:, :5]) # (n, [x1 y1 x2 y2 x3 y3 x4 y4])
seen += 1
if webcam: # batch_size >= 1
p, im0, frame = path[i], im0s[i].copy(), dataset.count
s += f'{i}: '
else:
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
p = Path(p) # to Path
save_path = str(save_dir / p.name) # im.jpg
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
s += '%gx%g ' % im.shape[2:] # print string
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
imc = im0.copy() if save_crop else im0 # for save_crop
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
if len(det):
# Rescale polys from img_size to im0 size
# det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
pred_poly = scale_polys(im.shape[2:], pred_poly, im0.shape)
det = torch.cat((pred_poly, det[:, -2:]), dim=1) # (n, [poly conf cls])
# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
# Write results
for *poly, conf, cls in reversed(det):
if save_txt: # Write to file
# xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
poly = poly.tolist()
line = (cls, *poly, conf) if save_conf else (cls, *poly) # label format
with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')
if save_img or save_crop or view_img: # Add poly to image
c = int(cls) # integer class
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
# annotator.box_label(xyxy, label, color=colors(c, True))
annotator.poly_label(poly, label, color=colors(c, True))
if save_crop: # Yolov5-obb doesn't support it yet
# save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
pass
# Print time (inference-only)
LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
# Stream results
im0 = annotator.result()
if view_img:
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
# Save results (image with detections)
if save_img:
if dataset.mode == 'image':
cv2.imwrite(save_path, im0)
else: # 'video' or 'stream'
if vid_path[i] != save_path: # new video
vid_path[i] = save_path
if isinstance(vid_writer[i], cv2.VideoWriter):
vid_writer[i].release() # release previous video writer
if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path += '.mp4'
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer[i].write(im0)
# Print results
t = tuple(x / seen * 1E3 for x in dt) # speeds per image
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
if update:
strip_optimizer(weights) # update model (to fix SourceChangeWarning)
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'runs/train/yolov5m_finetune/weights/best.pt', help='model path(s)')
parser.add_argument('--source', type=str, default='dataset/dataset_demo_rate1.0_split1024_gap200/images/', help='file/dir/URL/glob, 0 for webcam')
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640,640], help='inference size h,w')
parser.add_argument('--conf-thres', type=float, default=0.3, help='confidence threshold')
parser.add_argument('--iou-thres', type=float, default=0.4, help='NMS IoU threshold')
parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
parser.add_argument('--device', default='1', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--view-img', action='store_true', help='show results')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--visualize', action='store_true', help='visualize features')
parser.add_argument('--update', action='store_true', help='update all models')
parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
parser.add_argument('--name', default='exp', help='save results to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--line-thickness', default=2, type=int, help='bounding box thickness (pixels)')
parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
opt = parser.parse_args()
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
print_args(FILE.stem, opt)
return opt
def main(opt):
check_requirements(exclude=('tensorboard', 'thop'))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt)
python detect.py --weights xxx --source /path/
MP4對(duì)應(yīng)的文件夾下面會(huì)生成對(duì)應(yīng)的 xxx.txt
generate_config.py
"""
生成template_config.ini
"""
import os
import configparser
config = configparser.ConfigParser()
# with open('./template_config.ini','w') as f:
# pass
path = './template_config_fy.ini'
if os.path.exists(path):
os.remove(path)
config.read(path)
def getallfiles(path):
allfile = []
file_xml = []
for dirpath, dirnames, filenames in os.walk(path):
for dir in dirnames:
allfile.append(os.path.join(dirpath, dir))
for name in filenames:
allfile.append(os.path.join(dirpath, name))
for file in allfile:
if file.endswith('.tx',-4,-1):
file_xml.append(file)
return file_xml
txt_paths = getallfiles('./dataset/mp4/fy')
for txt_path in txt_paths:
# print(txt_path)
with open(txt_path,'r') as f:
content = f.readlines()
mid = int(len(content)/2)
tstart = content[0].replace(" >>>0",'')
tmid = content[mid].replace(" >>>0",'')
tend = content[-1].replace(" >>>0",'')
bn = os.path.basename(txt_path).split('.')[0]
config.add_section(bn)
# print(config[bn])
# print(tstart,tmid,tend)
# print(type(bn))
if "k" in txt_path:
type = 'open'
else:
type = 'close'
for cont in content :
config.set(bn, 'tstart',tstart.replace('\n',''))
config.set(bn, 'tmid',tmid.replace('\n',''))
config.set(bn, 'tend',tend.replace('\n',''))
config.set(bn, 'type',type.replace('\n',''))
config.set(bn, 'threshold','0.09')
config.write(open(path,'w'))