前言
????推理階段是整個(gè)檢測(cè)模型完成后,要對(duì)模型進(jìn)行測(cè)試的部分。很重要的一部分,只有了解了這個(gè)部分,才能在比賽或者項(xiàng)目提交中很好的輸出自己模型的檢測(cè)結(jié)果。同時(shí),推理輸出對(duì)模型部署在不同的環(huán)境下也是十分重要的。
源碼:https://github.com/ultralytics/yolov5
版本yolov5 v6.1
detect.py
1.輸入?yún)?shù)
@torch.no_grad() # 裝飾器,推理部分不進(jìn)行反向傳播計(jì)算
def run(
weights=ROOT / 'yolov5s.pt', # 加載的訓(xùn)練模型權(quán)重路徑
source=ROOT / 'data/images', # 輸入圖像或視頻文件路徑
data=ROOT / 'data/coco128.yaml', # dataset.yaml path,自己生成的數(shù)據(jù)集yaml文件路徑
imgsz=(640, 640), # inference size (height, width)
conf_thres=0.25, # confidence threshold
iou_thres=0.45, # NMS IOU threshold
max_det=1000, # maximum detections per image,默認(rèn)一張圖最多輸出1000個(gè)目標(biāo)
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu,選擇推理輸出的設(shè)備
view_img=False, # show results,推理后是否展示結(jié)果圖片
save_txt=False, # save results to *.txt,保存成.txt文件
save_conf=False, # save confidences in --save-txt labels,是否將置信度保存到txt文件
save_crop=False, # save cropped prediction boxes,是否將預(yù)測(cè)到的目標(biāo)從原圖剪切下來(lái)
nosave=False, # do not save images/videos,是否不保存推理輸出的結(jié)果
classes=None, # filter by class: --class 0, or --class 0 2 3,是否保留指定的類
agnostic_nms=False, # class-agnostic NMS,進(jìn)行nms時(shí)是否將其他類當(dāng)作同一個(gè)類別處理
augment=False, # augmented inference,是否進(jìn)行測(cè)試推理時(shí)的數(shù)據(jù)增強(qiáng),TTA之類的
visualize=False, # visualize features,是否可視化輸出
update=False, # update all models,
project=ROOT / 'runs/detect', # save results to project/name ,結(jié)果輸出保存主文件目錄
name='exp', # save results to project/name,結(jié)果輸出保存文件名稱
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,是否采用半精度浮點(diǎn)型進(jìn)行推理運(yùn)算
dnn=False, # use OpenCV DNN for ONNX inference
):
2.設(shè)置文件保存路徑
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://')) # 是否是網(wǎng)址
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,默認(rèn)路徑runs/detect/exp
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
3.加載訓(xùn)練好的模型權(quán)重
# Load model
device = select_device(device) # 選擇設(shè)備
# 不同的權(quán)重格式選擇不同的加載方式 ,如.pt,.onnx,.trt
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
stride, names, pt = model.stride, model.names, model.pt
imgsz = check_img_size(imgsz, s=stride) # check image size,檢查選擇輸入模型的尺寸是否符合32的倍數(shù)
4.數(shù)據(jù)處理
整個(gè)數(shù)據(jù)處理的步驟;
- 1.先對(duì)輸入圖像的原圖進(jìn)行最短邊的放縮;
- 2.為了匹配yolov5的下采樣操作還要使得輸入模型的寬高符合最后一次下采樣stride(三層一般32,四層64)的倍數(shù),還要對(duì)其進(jìn)行padding。
+3. 同時(shí),因?yàn)閛pencv讀取圖像是BGR格式,要將其轉(zhuǎn)化為RGB格式。 - 4.最后,還要對(duì)輸入的像素值進(jìn)行歸一化。
# Dataloader
if webcam:
view_img = check_imshow()
cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
bs = len(dataset) # batch_size
else:
# 這里只是簡(jiǎn)單的加載輸入圖像數(shù)據(jù)的路徑
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
bs = 1 # batch_size
vid_path, vid_writer = [None] * bs, [None] * bs
# Run inference
# 先進(jìn)行預(yù)熱,用全為0的先進(jìn)行一次推理,過一遍代碼
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
# 這里迭代的時(shí)候要進(jìn)入,utils/dataloaders.py里的__next__里進(jìn)行l(wèi)etterbox數(shù)據(jù)寬高放縮處理
for path, im, im0s, vid_cap, s in dataset:
t1 = time_sync() # 計(jì)算時(shí)間
im = torch.from_numpy(im).to(device) # 轉(zhuǎn)成tensor并將數(shù)據(jù)轉(zhuǎn)到cuda上
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32,選擇使用的精度,半浮點(diǎn)型速度要更快
im /= 255 # 0 - 255 to 0.0 - 1.0 這是像素值歸一化,跟坐標(biāo)歸一化無(wú)關(guān)
if len(im.shape) == 3:
im = im[None] # expand for batch dim,拓展一個(gè)batch維度
t2 = time_sync()
dt[0] += t2 - t1 # 計(jì)算數(shù)據(jù)預(yù)處理時(shí)間
- letterbox進(jìn)行resize和pad,opencv讀取的bgr轉(zhuǎn)成rgb
# Padded resize
img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0]
---------------------------------------------------------------------------
---------------------------------------------------------------------------
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
# Resize and pad image while meeting stride-multiple constraints
shape = im.shape[:2] # 輸入原圖高寬[height, width]
if isinstance(new_shape, int):
new_shape = (new_shape, new_shape)
# Scale ratio (new / old),求自己要求輸入模型圖像的高寬和原圖高寬的最小比值
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
if not scaleup: # only scale down, do not scale up (for better val mAP)
r = min(r, 1.0) # 這表示如果比值大于1不進(jìn)行比例縮放
# Compute padding
ratio = r, r # width, height ratios
# 對(duì)原圖寬高進(jìn)行最短邊比列縮放,保持寬高比不變,使圖像盡量不失真
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
# 為了符合32的倍數(shù)要求(滿足最小預(yù)測(cè)輸出的特征層),要對(duì)縮放的尺寸進(jìn)行padding
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
if auto: # minimum rectangle
dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding np.mod取模運(yùn)算
elif scaleFill: # stretch
dw, dh = 0.0, 0.0
new_unpad = (new_shape[1], new_shape[0])
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
dw /= 2 # divide padding into 2 sides
dh /= 2 # padding是對(duì)圖像兩邊進(jìn)行的
if shape[::-1] != new_unpad: # 和原圖寬高不等,opencv進(jìn)行resize
im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) # 四舍五入后取整
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
# padding的部分是無(wú)效區(qū)域,用color=(114, 114, 114)常數(shù)值填充,前面講mmdetection里的mask記錄放縮圖像無(wú)效區(qū)域一個(gè)意思
im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
# 返回縮放的寬高,比例和padding大小,方便后面對(duì)歸一化的預(yù)測(cè)輸出進(jìn)行還原,推理只要im
return im, ratio, (dw, dh)
---------------------------------------------------------------------------------
# opncv讀取的圖片數(shù)據(jù)是HWC和BGR格式的,為了方便要進(jìn)行處理
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return path, img, img0, self.cap, s
5.進(jìn)行推理
推理步驟:
- 1.將輸入圖像經(jīng)過模型得到預(yù)測(cè)輸出;
- 2.對(duì)預(yù)測(cè)輸出進(jìn)行NMS處理;
- 3.對(duì)NMS處理后的Boxes進(jìn)行相應(yīng)的后處理。
# Inference
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
# [b,num_pre_boxes,(5+cls_scores)]這里是輸出歸一化的boxes:x,y,h,w,5表示[x,y,h,w,conf]
pred = model(im, augment=augment, visualize=visualize)
t3 = time_sync()
dt[1] += t3 - t2 # 模型預(yù)測(cè)輸出時(shí)間
# 多類別的nms,部署的話要可以用opencv的,也可以用c++可以自己寫
# NMS,經(jīng)過下面的NMS后才是[num_P,6],[x1,y1,x2,y2,conf,cls]
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)# [x1,y1,x2,y2,conf,cls]
dt[2] += time_sync() - t3 # NMS的時(shí)間
# Process predictions
for i, det in enumerate(pred): # per image
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 boxes from img_size to im0 size,im:640,640,im0:原圖大小
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round() #還原原來(lái)圖像大小
# 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 *xyxy, conf, cls in reversed(det):
if save_txt: # Write to file
# xyxy2xywh:字面意思,將左上右下角的坐標(biāo)值,轉(zhuǎn)換為中心寬高值,再除以比例,歸一化保存到txt文件上
# 比賽或者項(xiàng)目里一般不會(huì)要求提交歸一化的結(jié)果,所以這里自己稍微進(jìn)行相應(yīng)的處理即可
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
# txt文件里每行記錄(cls, *xywh),如果要記錄置信度,將save_conf設(shè)置為true
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
# 打開txt文件,將推理的結(jié)果寫入
with open(f'{txt_path}.txt', 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')
# 后面的代碼都是保存和展示結(jié)果文件的了,這里就不解析了
if save_img or save_crop or view_img: # Add bbox 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))
if save_crop:
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
6.yolov5里的nms
在前面的博客,講了單類別的nms,但是如果是多類別的nms可以怎么做呢?
已知的方法:
- 第一種方法就是,對(duì)循環(huán)遍歷每類,然后每類進(jìn)行nms;
- 第二種方法,直接對(duì)所有的box進(jìn)行分?jǐn)?shù)降序排列,之后在循環(huán)里進(jìn)行判斷,只要類別相同的才進(jìn)行iou計(jì)算,然后再比較閾值。這要用一個(gè)標(biāo)記數(shù)組來(lái)記錄哪些是要篩選的,之后篩選掉。
- 第三種方法,使用一個(gè)偏移量,將不同的類加上一個(gè)偏移量,將每個(gè)類的所有box單獨(dú)變換到不同的坐標(biāo)域,直接按原來(lái)的進(jìn)行nms即可。
yolov5就是采用的第三種方法,這里這要講下主要的代碼,完整代碼在utils/general.py里的non_max_suppression里
# 主要代碼
max_wh = 7680 # 最大寬高
----------------------------------------------------------
# 這里的代碼主要解釋x的維度代表什么,下面有用到
# 找出的conf_thres(類別分?jǐn)?shù)*置信度)最大的對(duì)應(yīng)的一個(gè)類和索引,j是類別label的索引(其實(shí)就是類別標(biāo)簽):[0,1,1,2]這種
conf, j = x[:, 5:].max(1, keepdim=True)
# 在維度1上重新合并[經(jīng)過初步分?jǐn)?shù)閾值篩選的預(yù)測(cè)數(shù)量,4+1+1=6],取出大于conf_thres閾值的預(yù)測(cè)值[k,6]
x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
---------------------------------------------------------
# 進(jìn)行多類別的nms
# Batched NMS,如果agnostic為true,表示所有的作為一類進(jìn)行nms,默認(rèn)false,每類乘上一個(gè)最大wh長(zhǎng)度的偏移值
c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
# 之后在boxes上加上偏移量作為iou計(jì)算的boxes
boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
總結(jié)
????推理輸出部分的理解是十分重要的,在比賽和項(xiàng)目中有提交結(jié)果格式的要求,都要在這修改相應(yīng)的代碼。同時(shí),也可以在推理過程中使用一些trick去提升性能。同時(shí),為了實(shí)時(shí)性,算法的開發(fā)部署主要就是推理階段的部署。為了加速推理速度,提升檢測(cè)性能,可以很好的將訓(xùn)練好的torch模型轉(zhuǎn)換成onnx或者engine,使用c++進(jìn)行部署。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-442652.html
yolov5 系列
yolov5使用自己的數(shù)據(jù)集相關(guān)代碼
yolov5網(wǎng)絡(luò)結(jié)構(gòu)代碼解讀
yolov5的正負(fù)樣本的定義和匹配文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-442652.html
到了這里,關(guān)于yolov5的推理輸出detect.py部分的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!