当前位置:   article > 正文

5分钟让你的电脑运行yolo图像识别

yolo图像识别

首先我们需要安装python3.8以上,具体安装方法就不多说了

我这里已经安装好了

第二步,安装依赖包

打开CMD,然后CD到yolo文件夹的位置上,然后pip install -r requirements.txt。等待他自己下载安装依赖包。

这里我已经全部下载好了。

第三步,打开IDLE(第一步已经安装), CTRL+O,然后打开yolo文件夹中的Untitled-1.py文件。

 

  1. import cv2
  2. import numpy as np
  3. # Load Yolo
  4. print("LOADING YOLO")
  5. net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
  6. #save all the names in file o the list classes
  7. classes = []
  8. with open("coco.names", "r") as f:
  9. classes = [line.strip() for line in f.readlines()]
  10. #get layers of the network
  11. layer_names = net.getLayerNames()
  12. #Determine the output layer names from the YOLO model
  13. output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
  14. colors = np.random.uniform(0, 255, size=(len(classes), 3))
  15. print("YOLO LOADED")
  16. img = cv2.imread("room.png")
  17. img = cv2.resize(img,None,fx = 0.4,fy = 0.4)
  18. height, width, channel = img.shape
  19. print(width,height,channel)
  20. # Detect Objects
  21. blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
  22. net.setInput(blob)
  23. outs = net.forward(output_layers)
  24. # print(outs)
  25. print(width,height,channel)
  26. ####################################
  27. # Showing Information on the screen
  28. class_ids = []
  29. confidences = []
  30. boxes = []
  31. for out in outs:
  32. for detection in out:
  33. scores = detection[5:]
  34. class_id = np.argmax(scores)
  35. confidence = scores[class_id]
  36. if confidence > 0.5:
  37. # Object detection
  38. center_x = int(detection[0] * width)
  39. center_y = int(detection[1] * height)
  40. w = int(detection[2] * width)
  41. h = int(detection[3] * height)
  42. # cv.circle(img, (center_x, center_y), 10, (0, 255, 0), 2 )
  43. # Reactangle Cordinate
  44. x = int(center_x - w/2)
  45. y = int(center_y - h/2)
  46. boxes.append([x, y, w, h])
  47. confidences.append(float(confidence))
  48. class_ids.append(class_id)
  49. # print(len(boxes))
  50. # number_object_detection = len(boxes)
  51. indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
  52. print(indexes)
  53. font = cv2.FONT_HERSHEY_PLAIN
  54. for i in range(len(boxes)):
  55. if i in indexes:
  56. x, y, w, h = boxes[i]
  57. label = str(classes[class_ids[i]])
  58. # print(label)
  59. color = colors[i]
  60. cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
  61. cv2.putText(img, label, (x, y + 30), font, 3, color, 3)
  62. cv2.imshow("IMG", img)
  63. cv2.waitKey(0)
  64. cv2.destroyAllWindows()

第四步,按下F5运行程序,就能看到room.png这张照片中的物体被识别出来。

 当然,如果你会开启USB摄像头,就可以获得实时显示识别的效果。

文件地址:

链接:https://pan.baidu.com/s/1JT1K7q2-PR9pAYNBV-3DtQ?pwd=qnlo 
提取码:qnlo

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/818185
推荐阅读
相关标签
  

闽ICP备14008679号