日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

深度学习和目标检测系列教程 15-300:在 Python 中使用 OpenCV 执行 YOLOv3 对象检测

發布時間:2024/10/8 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 深度学习和目标检测系列教程 15-300:在 Python 中使用 OpenCV 执行 YOLOv3 对象检测 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

@Author:Runsen

上次講了yolov3,這是使用yolov3的模型通過opencv的攝像頭來執行YOLOv3 對象檢測。

導入所需模塊:

import cv2 import numpy as np import time

讓我們定義一些我們需要的變量和參數:

CONFIDENCE = 0.5 SCORE_THRESHOLD = 0.5 IOU_THRESHOLD = 0.5# network configuration config_path = "cfg/yolov3.cfg" # YOLO net weights weights_path = "weights/yolov3.weights" # coco class labels (objects) labels = open("data/coco.names").read().strip().split("\n") # 每一個對象的檢測框的顏色 colors = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8")

config_path和weights_path 分別代表yolov3模型配置 和對應的預訓練模型權重。

  • yolov3.cfg下載:https://github.com/pjreddie/darknet/blob/master/cfg/yolov3.cfg
  • coco.names下載:https://github.com/pjreddie/darknet/blob/master/data/coco.names
  • yolov3.weights下載:https://pjreddie.com/media/files/yolov3.weights

labels是檢測的不同對象的所有類標簽的列表,生成隨機顏色
是因為有很多類的存在。

下面的代碼加載模型:

net = cv2.dnn.readNetFromDarknet(config_path, weights_path)

先加載一個示例圖像:

path_name = "test.jpg" image = cv2.imread(path_name) file_name = os.path.basename(path_name) filename, ext = file_name.split(".") h, w = image.shape[:2]

接下來,需要對這個圖像進行歸一化、縮放和整形,使其適合作為神經網絡的輸入:

# create 4D blob blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)

這會將像素值標準化為從0到1 的范圍,將圖像大小調整為(416, 416)并對其進行縮放

print("image.shape:", image.shape) print("blob.shape:", blob.shape)image.shape: (1200, 1800, 3) blob.shape: (1, 3, 416, 416)

現在讓我們將此圖像輸入神經網絡以獲得輸出預測:

# 將blob設置為網絡的輸入 net.setInput(blob) # 獲取所有圖層名稱 ln = net.getLayerNames() ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()] #得到網絡輸出 #測量一下時間花費 start = time.perf_counter() layer_outputs = net.forward(ln) time_took = time.perf_counter() - start print(f"Time took: {time_took:.2f}s")boxes, confidences, class_ids = [], [], []# 在每個層輸出上循環 for output in layer_outputs:# 在每一個物體上循環''' detection.shape等于85,前4 個值代表物體的位置,(x, y)坐標為中心點和邊界框的寬度和高度,其余數字對應物體標簽,因為這是COCO 數據集,它有80類標簽。例如,如果檢測到的對象是人,則80長度向量中的第一個值應為1,其余所有值應為0,自行車的第二個數字,汽車的第三個數字,一直到第 80 個對象。然后使用np.argmax() 函數來獲取類 id 的原因,因為它返回80長度向量中最大值的索引。 ''' for detection in output:# 提取類id(標簽)和置信度(作為概率)# 當前目標檢測scores = detection[5:]class_id = np.argmax(scores)confidence = scores[class_id]if confidence > CONFIDENCE:# 將邊界框坐標相對于# 圖像的大小,記住YOLO實際上# 返回邊界的中心(x,y)坐標# 框,然后是框的寬度和高度box = detection[:4] * np.array([w, h, w, h])(centerX, centerY, width, height) = box.astype("int")# 使用中心(x,y)坐標導出x和y# 和邊界框的左角x = int(centerX - (width / 2))y = int(centerY - (height / 2))# 更新邊界框坐標,信任度,和類IDboxes.append([x, y, int(width), int(height)])confidences.append(float(confidence))class_ids.append(class_id) #根據前面定義的分數執行非最大值抑制 idxs = cv2.dnn.NMSBoxes(boxes, confidences, SCORE_THRESHOLD, IOU_THRESHOLD) font_scale = 1 thickness = 1 # 確保至少存在一個檢測 if len(idxs) > 0:# 循環查看我們保存的索引for i in idxs.flatten():# 提取邊界框坐標x, y = boxes[i][0], boxes[i][1]w, h = boxes[i][2], boxes[i][3]# 在圖像上繪制邊框矩形和標簽color = [int(c) for c in colors[class_ids[i]]]cv2.rectangle(image, (x, y), (x + w, y + h), color=color, thickness=thickness)text = f"{labels[class_ids[i]]}: {confidences[i]:.2f}"# 計算文本寬度和高度以繪制透明框作為文本背景(text_width, text_height) = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, fontScale=font_scale, thickness=thickness)[0]text_offset_x = xtext_offset_y = y - 5box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height))overlay = image.copy()cv2.rectangle(overlay, box_coords[0], box_coords[1], color=color, thickness=cv2.FILLED)#添加(長方體的透明度)image = cv2.addWeighted(overlay, 0.6, image, 0.4, 0)cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,fontScale=font_scale, color=(0, 0, 0), thickness=thickness)cv2.imwrite(filename + "_yolo3." + ext, image)


一張圖片的時間需要1.3秒。

Time took: 1.32s

下面結合opencv讀取攝像頭的功能,實現攝像頭的拍攝畫面的識別

import cv2 import numpy as np import time CONFIDENCE = 0.5 SCORE_THRESHOLD = 0.5 IOU_THRESHOLD = 0.5 config_path = "cfg/yolov3.cfg" weights_path = "weights/yolov3.weights" font_scale = 1 thickness = 1 LABELS = open("data/coco.names").read().strip().split("\n") COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8") net = cv2.dnn.readNetFromDarknet(config_path, weights_path) ln = net.getLayerNames() ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()] cap = cv2.VideoCapture(0) while True:_, image = cap.read()h, w = image.shape[:2]blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)net.setInput(blob)start = time.perf_counter()layer_outputs = net.forward(ln)time_took = time.perf_counter() - startprint("Time took:", time_took)boxes, confidences, class_ids = [], [], []for output in layer_outputs:for detection in output:scores = detection[5:]class_id = np.argmax(scores)confidence = scores[class_id]if confidence > CONFIDENCE:box = detection[:4] * np.array([w, h, w, h])(centerX, centerY, width, height) = box.astype("int")x = int(centerX - (width / 2))y = int(centerY - (height / 2))boxes.append([x, y, int(width), int(height)])confidences.append(float(confidence))class_ids.append(class_id)idxs = cv2.dnn.NMSBoxes(boxes, confidences, SCORE_THRESHOLD, IOU_THRESHOLD)font_scale = 1thickness = 1if len(idxs) > 0:for i in idxs.flatten():x, y = boxes[i][0], boxes[i][1]w, h = boxes[i][2], boxes[i][3]color = [int(c) for c in COLORS[class_ids[i]]]cv2.rectangle(image, (x, y), (x + w, y + h), color=color, thickness=thickness)text = f"{LABELS[class_ids[i]]}: {confidences[i]:.2f}"(text_width, text_height) = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, fontScale=font_scale, thickness=thickness)[0]text_offset_x = xtext_offset_y = y - 5box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height))overlay = image.copy()cv2.rectangle(overlay, box_coords[0], box_coords[1], color=color, thickness=cv2.FILLED)image = cv2.addWeighted(overlay, 0.6, image, 0.4, 0)cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,fontScale=font_scale, color=(0, 0, 0), thickness=thickness)cv2.imshow("image", image)if ord("q") == cv2.waitKey(1):breakcap.release() cv2.destroyAllWindows()

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的深度学习和目标检测系列教程 15-300:在 Python 中使用 OpenCV 执行 YOLOv3 对象检测的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。