因为要做个暑期项目,队友是通过oss来存储图片,不是本地识别,要从链接来识别。又因为打开文件是字节流,不是图片格式,所以就直接用opencv的视频功能来完成。
在detect.py文件下。
1.首先是配置,该改的配置如下,其他可以
def run(weights='runs/train/exp5/weights/best.pt', # model.pt path(s) 你训练好的模型
source='https://tourist-insect.oss-cn-shanghai.aliyuncs.com/tmp/2021/07/21/16268285775224793.jpg', # 这个就是你要识别图片的url
imgsz=640, # inference size (pixels)
conf_thres=0.25, # confidence threshold
iou_thres=0.45, # 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=True, # 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='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
):
2.其次就是获取图片并保存到本地
这一步是将图片保存为temp.jpg
cap = cv2.VideoCapture(source)
if( cap.isOpened() ):
ret, img = cap.read()
img = cv2.resize(img, (640, 640))
cv2.imwrite("temp.jpg", img)#将网络的图片存到本地
有的图片cap.isOpened()是False,那么可以用另一种方法
resp = urllib.request.urlopen(source)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imwrite("temp.jpg", image)
3.最后加入数据集
dataset = LoadImages('temp.jpg', img_size=imgsz, stride=stride)