如何修改yolov5-7.0中detect.py源码,将未识别出来的图片保存到新文件夹
时间: 2024-02-04 14:04:09 浏览: 172
要修改yolov5-7.0中detect.py源码,将未识别出来的图片保存到新文件夹,可以按照以下步骤进行操作:
1. 在detect.py源码中找到以下代码段:
```
# Process detections
for i, det in enumerate(detections): # detections per image
if webcam: # batch_size >= 1
p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
else:
p, s, im0 = path, '', im0s
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img_size, det[:, :4], im0.shape).round()
# 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 det:
if save_img 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}')
plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=3)
print(f'{s}Done. ({t2 - t1:.3f}s)')
# Stream results
if view_img:
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
# Save results (image with detections)
if save_img:
if dataset.mode == 'images':
cv2.imwrite(save_path / p, im0)
else: # 'video'
if vid_path != save_path: # new video
vid_path = save_path / Path(p).stem + suffix
if vid_writer is not None:
vid_writer.release() # release previous video writer
fourcc = 'mp4v' # output video codec
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))
vid_writer = cv2.VideoWriter(str(vid_path), cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))
vid_writer.write(im0)
if save_txt or save_img:
print(f"Results saved to {colorstr('bold', save_path)}")
if platform == 'darwin' and not update: # MacOS
os.system('open ' + str(save_path))
```
2. 在上述代码段中添加以下代码段,用于将未识别出来的图片保存到新文件夹中:
```
# Save images without detections
if save_img:
if dataset.mode == 'images':
if len(det) == 0:
cv2.imwrite(save_path_no_detection / p, im0)
else: # 'video'
if len(det) == 0:
if vid_path_no_detection != save_path_no_detection: # new video
vid_path_no_detection = save_path_no_detection / Path(p).stem + suffix
if vid_writer_no_detection is not None:
vid_writer_no_detection.release() # release previous video writer
fourcc = 'mp4v' # output video codec
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))
vid_writer_no_detection = cv2.VideoWriter(str(vid_path_no_detection), cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))
vid_writer_no_detection.write(im0)
```
3. 保存detect.py源码并重新运行程序即可看到未识别出来的图片被保存到新文件夹中。
阅读全文