欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

OpenCV+python實(shí)現(xiàn)實(shí)時(shí)目標(biāo)檢測(cè)功能

 更新時(shí)間:2020年06月24日 11:42:05   作者:JaksionTang  
這篇文章主要介紹了OpenCV+python實(shí)現(xiàn)實(shí)時(shí)目標(biāo)檢測(cè)功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

環(huán)境安裝

  1. 安裝Anaconda,官網(wǎng)鏈接Anaconda
  2. 使用conda創(chuàng)建py3.6的虛擬環(huán)境,并激活使用
conda create -n py3.6 python=3.6 //創(chuàng)建
	conda activate py3.6 //激活

在這里插入圖片描述

3.安裝依賴numpy和imutils

//用鏡像安裝
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple imutils

4.安裝opencv

(1)首先下載opencv(網(wǎng)址:opencv),在這里我選擇的是opencv_python‑4.1.2+contrib‑cp36‑cp36m‑win_amd64.whl 。
(2)下載好后,把它放到任意盤(pán)中(這里我放的是D盤(pán)),切換到安裝目錄,執(zhí)行安裝命令:pip install opencv_python‑4.1.2+contrib‑cp36‑cp36m‑win_amd64.whl

代碼

首先打開(kāi)一個(gè)空文件命名為real_time_object_detection.py,加入以下代碼,導(dǎo)入你所需要的包。

# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import time
import cv2

2.我們不需要圖像參數(shù),因?yàn)樵谶@里我們處理的是視頻流和視頻——除了以下參數(shù)保持不變:
–prototxt:Caffe prototxt 文件路徑。
–model:預(yù)訓(xùn)練模型的路徑。
–confidence:過(guò)濾弱檢測(cè)的最小概率閾值,默認(rèn)值為 20%。

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
	help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
	help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2,
	help="minimum probability to filter weak detections")
args = vars(ap.parse_args())

3.初始化類列表和顏色集,我們初始化 CLASS 標(biāo)簽,和相應(yīng)的隨機(jī) COLORS。

# initialize the list of class labels MobileNet SSD was trained to
# detect, then generate a set of bounding box colors for each class
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
	"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
	"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
	"sofa", "train", "tvmonitor"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

4.加載自己的模型,并設(shè)置自己的視頻流。

# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

# initialize the video stream, allow the cammera sensor to warmup,
# and initialize the FPS counter
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
fps = FPS().start()

首先我們加載自己的序列化模型,并且提供對(duì)自己的 prototxt文件 和模型文件的引用
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
下一步,我們初始化視頻流(來(lái)源可以是視頻文件或攝像頭)。首先,我們啟動(dòng) VideoStreamvs = VideoStream(src=0).start(),隨后等待相機(jī)啟動(dòng)time.sleep(2.0),最后開(kāi)始每秒幀數(shù)計(jì)算fps = FPS().start()。VideoStream 和 FPS 類是 imutils 包的一部分。

5.遍歷每一幀

# loop over the frames from the video stream
while True:
	# grab the frame from the threaded video stream and resize it
	# to have a maximum width of 400 pixels
	frame = vs.read()
	frame = imutils.resize(frame, width=400)

	# grab the frame from the threaded video file stream
	(h, w) = frame.shape[:2]
	blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),
		0.007843, (300, 300), 127.5)

	# pass the blob through the network and obtain the detections and
	# predictions
	net.setInput(blob)
	detections = net.forward()

首先,從視頻流中讀取一幀frame = vs.read(),隨后調(diào)整它的大小imutils.resize(frame, width=400)。由于我們隨后會(huì)需要寬度和高度,接著進(jìn)行抓取(h, w) = frame.shape[:2]。最后將 frame 轉(zhuǎn)換為一個(gè)有 dnn 模塊的 blob,cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),0.007843, (300, 300), 127.5)。
現(xiàn)在,我們?cè)O(shè)置 blob 為神經(jīng)網(wǎng)絡(luò)的輸入net.setInput(blob),通過(guò) net 傳遞輸入detections = net.forward()

6.這時(shí),我們已經(jīng)在輸入幀中檢測(cè)到了目標(biāo),現(xiàn)在看看置信度的值,來(lái)判斷我們能否在目標(biāo)周圍繪制邊界框和標(biāo)簽。

# loop over the detections
	for i in np.arange(0, detections.shape[2]):
		# extract the confidence (i.e., probability) associated with
		# the prediction
		confidence = detections[0, 0, i, 2]

		# filter out weak detections by ensuring the `confidence` is
		# greater than the minimum confidence
		if confidence > args["confidence"]:
			# extract the index of the class label from the
			# `detections`, then compute the (x, y)-coordinates of
			# the bounding box for the object
			idx = int(detections[0, 0, i, 1])
			box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
			(startX, startY, endX, endY) = box.astype("int")

			# draw the prediction on the frame
			label = "{}: {:.2f}%".format(CLASSES[idx],
				confidence * 100)
			cv2.rectangle(frame, (startX, startY), (endX, endY),
				COLORS[idx], 2)
			y = startY - 15 if startY - 15 > 15 else startY + 15
			cv2.putText(frame, label, (startX, y),
				cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)

在 detections 內(nèi)循環(huán),一個(gè)圖像中可以檢測(cè)到多個(gè)目標(biāo)。因此我們需要檢查置信度。如果置信度足夠高(高于閾值),那么將在終端展示預(yù)測(cè),并以文本和彩色邊界框的形式對(duì)圖像作出預(yù)測(cè)。
在 detections 內(nèi)循環(huán),首先我們提取 confidence 值,confidence = detections[0, 0, i, 2]。如果 confidence 高于最低閾值(if confidence > args["confidence"]:),那么提取類標(biāo)簽索引(idx = int(detections[0, 0, i, 1])),并計(jì)算檢測(cè)到的目標(biāo)的坐標(biāo)(box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]))。然后,我們提取邊界框的 (x, y) 坐標(biāo)((startX, startY, endX, endY) = box.astype("int")),將用于繪制矩形和文本。接著構(gòu)建一個(gè)文本 label,包含 CLASS 名稱和 confidence(label = "{}: {:.2f}%".format(CLASSES[idx],confidence * 100))。還要使用類顏色和之前提取的 (x, y) 坐標(biāo)在物體周圍繪制彩色矩形(cv2.rectangle(frame, (startX, startY), (endX, endY),COLORS[idx], 2))。如果我們希望標(biāo)簽出現(xiàn)在矩形上方,但是如果沒(méi)有空間,我們將在矩形頂部稍下的位置展示標(biāo)簽(y = startY - 15 if startY - 15 > 15 else startY + 15)。最后,我們使用剛才計(jì)算出的 y 值將彩色文本置于幀上(cv2.putText(frame, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2))。

7.幀捕捉循環(huán)剩余的步驟還包括:展示幀;檢查 quit 鍵;更新 fps 計(jì)數(shù)器。

	# show the output frame
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF

	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		break

	# update the FPS counter
	fps.update()

上述代碼塊簡(jiǎn)單明了,首先我們展示幀(cv2.imshow("Frame", frame)),然后找到特定按鍵(key = cv2.waitKey(1) & 0xFF),同時(shí)檢查「q」鍵(代表「quit」)是否按下。如果已經(jīng)按下,則我們退出幀捕捉循環(huán)(if key == ord("q"):break),最后更新 fps 計(jì)數(shù)器(fps.update())。

8.退出了循環(huán)(「q」鍵或視頻流結(jié)束),我們還要處理以下。

# stop the timer and display FPS information
fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()

運(yùn)行文件目錄有以下文件:

在這里插入圖片描述

到文件相應(yīng)的目錄下:cd D:\目標(biāo)檢測(cè)\object-detection執(zhí)行命令:python real_time_object_detection.py --prototxt MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel

在這里插入圖片描述

演示

這里我把演示視頻上傳到了B站,地址鏈接目標(biāo)檢測(cè)

補(bǔ)充

項(xiàng)目github地址object_detection鏈接。
本項(xiàng)目要用到MobileNetSSD_deploy.prototxt.txtMobileNetSSD_deploy.caffemodel,可以去github上下載項(xiàng)目運(yùn)行。

到此這篇關(guān)于OpenCV+python實(shí)現(xiàn)實(shí)時(shí)目標(biāo)檢測(cè)功能的文章就介紹到這了,更多相關(guān)python實(shí)現(xiàn)目標(biāo)檢測(cè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • ruff check文件目錄檢測(cè)--exclude參數(shù)設(shè)置路徑詳解

    ruff check文件目錄檢測(cè)--exclude參數(shù)設(shè)置路徑詳解

    這篇文章主要為大家介紹了ruff check文件目錄檢測(cè)exclude參數(shù)如何設(shè)置多少路徑詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10
  • python中opencv?直方圖處理

    python中opencv?直方圖處理

    這篇文章主要介紹了python中opencv?直方圖處理,直方圖從圖像內(nèi)部灰度級(jí)的角度對(duì)圖像進(jìn)行表述,直方圖是圖像內(nèi)灰度值的統(tǒng)計(jì)特性與圖像灰度值之間的函數(shù),直方圖統(tǒng)計(jì)圖像內(nèi)各個(gè)灰度級(jí)出現(xiàn)的次數(shù),更多相關(guān)內(nèi)容需要的小伙伴可以參考一下
    2022-06-06
  • Python項(xiàng)目跨域問(wèn)題解決方案

    Python項(xiàng)目跨域問(wèn)題解決方案

    這篇文章主要介紹了Python項(xiàng)目跨域問(wèn)題解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • python opencv把一張圖片嵌入(疊加)到另一張圖片上的實(shí)現(xiàn)代碼

    python opencv把一張圖片嵌入(疊加)到另一張圖片上的實(shí)現(xiàn)代碼

    這篇文章主要介紹了python opencv把一張圖片嵌入(疊加)到另一張圖片上,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-06-06
  • Python簡(jiǎn)易計(jì)算器制作方法代碼詳解

    Python簡(jiǎn)易計(jì)算器制作方法代碼詳解

    這篇文章主要介紹了Python簡(jiǎn)易計(jì)算器制作方法,文中代碼主要用到了python中的tkinter庫(kù),代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-10-10
  • 如何用python將單引號(hào)替換為雙引號(hào)

    如何用python將單引號(hào)替換為雙引號(hào)

    這篇文章主要介紹了如何用python將單引號(hào)替換為雙引號(hào),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Python+Delorean實(shí)現(xiàn)時(shí)間格式智能轉(zhuǎn)換

    Python+Delorean實(shí)現(xiàn)時(shí)間格式智能轉(zhuǎn)換

    DeLorean是一個(gè)Python的第三方模塊,基于?pytz?和?dateutil?開(kāi)發(fā),用于處理Python中日期時(shí)間的格式轉(zhuǎn)換。本文將詳細(xì)講講DeLorean的使用,感興趣的可以了解一下
    2022-04-04
  • 使用tensorflow實(shí)現(xiàn)線性回歸

    使用tensorflow實(shí)現(xiàn)線性回歸

    這篇文章主要為大家詳細(xì)介紹了使用tensorflow實(shí)現(xiàn)線性回歸,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • python爬蟲(chóng)MeterSphere平臺(tái)執(zhí)行報(bào)告使用實(shí)戰(zhàn)

    python爬蟲(chóng)MeterSphere平臺(tái)執(zhí)行報(bào)告使用實(shí)戰(zhàn)

    這篇文章主要為大家介紹了python爬蟲(chóng)MeterSphere平臺(tái)執(zhí)行報(bào)告使用實(shí)戰(zhàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • python3連接mysql獲取ansible動(dòng)態(tài)inventory腳本

    python3連接mysql獲取ansible動(dòng)態(tài)inventory腳本

    Ansible Inventory 是包含靜態(tài) Inventory 和動(dòng)態(tài) Inventory 兩部分的,靜態(tài) Inventory 指的是在文件中指定的主機(jī)和組,動(dòng)態(tài) Inventory 指通過(guò)外部腳本獲取主機(jī)列表。這篇文章主要介紹了python3連接mysql獲取ansible動(dòng)態(tài)inventory腳本,需要的朋友可以參考下
    2020-01-01

最新評(píng)論