1.网上有很多网络摄像头跑yolo的案例,但是,不行。网络摄像头和工业相机不一样!yolo是能直接检测网络摄像头的视频的(这个我没有试过,因为没有网络摄像头)
./darknet detector demo cfg/coco.data cfg/yolov3.cfg yolov3.weights rtsp://admin:password@192.168.1.64
()
我试了一下调用手机摄像头进行检测,可行(忘了从哪里看见的)
先在手机上下载一个IP摄像头(这个华为应用商城能下到,比较方便)
./darknet detector demo cfg/coco.data cfg/yolov3.cfg yolov3.weights http://admin:admin@192.168.31.33:8080
@后面的是自己手机的IP地址,我的是局域网的IP(IP摄像头-打开IP摄像头服务器-局域网或者连接里有)
总结:网络摄像头有自己的IP,有http和rtsp协议,但是工业相机莫得
2.用python调用海康工业相机实现yolov3检测
首先,要右键以管理员身份运行一下文件,具体我也不太懂,看别人的,反正我跑通了
()
这一步主要是可以让我调用这个命令:
cap = cv2.VideoCapture(1)
下面是完整代码:
#摄像头运行yolo import cv2 import numpy as np import time # 下载权重文件、配置文件 net = cv2.dnn.readNet("backup/sorting_final.weights", "obj/yolov3-voc.cfg") classes = [] with open("obj/voc.names", "r") as f: classes = [line.strip() for line in f.readlines()] layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] colors = np.random.uniform(0, 255, size=(len(classes), 3)) # 输入待检测视频、或打开摄像头实时检测 cap = cv2.VideoCapture(1) # 参数为0是打开笔记本摄像头,用摄像头实时检测 #cap = cv2.VideoCapture("walking.mp4") # 参数为文件名表示打开视频 if False == cap.isOpened(): print(0) else: print(1) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) # 设置图像宽度(根据自己相机的像素) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1200) # 设置图像高度 cap.set(cv2.CAP_PROP_FPS, 20) # 设置帧率 font = cv2.FONT_HERSHEY_PLAIN starting_time = time.time() frame_id = 0 while True: _, frame = cap.read() frame_id += 1 height, width, channels = frame.shape # 检测对象 blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) # 在屏幕上显示信息 class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.2: # 目标检测 center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) # 绘制矩形框 x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.8, 0.3) for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) confidence = confidences[i] color = colors[class_ids[i]] cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) cv2.putText(frame, label + " " + str(round(confidence, 2)), (x, y + 30), font, 3, color, 3) elapsed_time = time.time() - starting_time fps = frame_id / elapsed_time cv2.putText(frame, "FPS: " + str(round(fps, 2)), (10, 50), font, 4, (0, 0, 0), 3) cv2.imshow("Image", frame) key = cv2.waitKey(1) if key == 27: break cap.release() cv2.destroyAllWindows()
(代码:)
注意:此时我电脑除了笔记本摄像头,只外连接了一个海康工业相机,所以这个cap = cv2.VideoCapture(1)语句可以直接无脑填1(0是笔记本,1是我的海康),如果此时有多个外连接相机,要列举相机,找到相机编号才可以,因为我只有一个相机,所以没有试过。(在上一个连接里有)
结果:运行很卡,我还没有看到底帧数是多少,后期补一下,但是我成功了,已经很开心