通過實(shí)際示例學(xué)習(xí)計(jì)算機(jī)視覺和機(jī)器學(xué)習(xí)的基本技術(shù)
OpenCV 是一個(gè)開源的計(jì)算機(jī)視覺庫(kù),廣泛應(yīng)用于計(jì)算機(jī)視覺和機(jī)器學(xué)習(xí)領(lǐng)域。它提供了廣泛的圖像和視頻處理工具,包括特征檢測(cè)、圖像識(shí)別和對(duì)象跟蹤。
在本文中,我們將了解如何使用 OpenCV 執(zhí)行各種任務(wù),重點(diǎn)是如何使用它來應(yīng)用機(jī)器學(xué)習(xí)。
首先,讓我們從安裝開始,你需要在你的環(huán)境中安裝 OpenCV 庫(kù),你可以通過運(yùn)行以下命令來完成此操作:
pip install opencv-python
或者
conda install -c conda-forge opencv
一旦安裝了 OpenCV,就可以開始在 Python 代碼中使用它。以下是如何讀取圖像文件并顯示它的示例:
import cv2
# read the image
image = cv2.imread("image.jpg")
# display the image
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
OpenCV 還提供了廣泛的圖像處理功能。以下是如何將圖像轉(zhuǎn)換為灰度并顯示它的示例:
import cv2
# read the image
image = cv2.imread("image.jpg")
# convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# display the image
cv2.imshow("Grayscale Image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
OpenCV 的另一個(gè)重要特性是它能夠檢測(cè)圖像中的特征。例如,你可以使用 OpenCV 的cv2.CascadeClassifier類來檢測(cè)圖像中的人臉:
import cv2
# read the image
image = cv2.imread("image.jpg")
# create the classifier
classifier = cv2.CascadeClassifier("path_to_classifier_xml")
# detect faces
faces = classifier.detectMultiScale(image, scaleFactor=1.3, minNeighbors=5)
# draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
# display the image
cv2.imshow("Faces", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
OpenCV 還提供了許多基于機(jī)器學(xué)習(xí)的功能,例如檢測(cè)、識(shí)別和跟蹤。例如,你可以使用cv2.ml模塊來訓(xùn)練和使用機(jī)器學(xué)習(xí)模型。
import cv2
import numpy as np
# create the feature and label vectors
features = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
labels = np.array([1, 2, 3, 4])
# create the SVM model
svm = cv2.ml.SVM_create()
svm.setType(cv2.ml.SVM_C_SVC)
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.setC(1.0)
# train the model
svm.train(features, cv2.ml.ROW_SAMPLE, labels)
# test the model on new data
new_data = np.array([[2, 3], [4, 5]]) result = svm.predict(new_data) print(result[1])
在上面的示例中,我們使用cv2.ml模塊創(chuàng)建了一個(gè) SVM 模型,設(shè)置了模型的參數(shù),使用我們的特征和標(biāo)簽向量對(duì)其進(jìn)行了訓(xùn)練,然后在新數(shù)據(jù)上對(duì)其進(jìn)行了測(cè)試。
另一個(gè)例子是使用深度學(xué)習(xí),你可以使用OpenCV的cv2.dnn模塊來加載和使用預(yù)訓(xùn)練的深度學(xué)習(xí)模型cv2.dnn.readNetFromCaffe,這是一個(gè)基于Caffe的深度學(xué)習(xí)模型。
import cv2
# read the image
image = cv2.imread("image.jpg")
# load the deep learning model
net = cv2.dnn.readNetFromCaffe("path_to_prototxt", "path_to_caffe_model")
# set the input blob
blob = cv2.dnn.blobFromImage(image, 1.0, (224, 224), (104, 117, 123))
net.setInput(blob)
# get the predictions
predictions = net.forward()
# display the predictions
print(predictions)
在上面的示例中,我們使用cv2.dnn模塊加載了一個(gè)深度學(xué)習(xí)模型,設(shè)置了輸入 blob,然后使用該模型對(duì)我們的圖像進(jìn)行預(yù)測(cè)。
這些是你如何將 OpenCV 用于計(jì)算機(jī)視覺和機(jī)器學(xué)習(xí)任務(wù)的幾個(gè)示例。OpenCV 擁有廣泛的工具和功能,是一個(gè)強(qiáng)大的庫(kù),可供數(shù)據(jù)科學(xué)家用于滿足他們的計(jì)算機(jī)視覺和機(jī)器學(xué)習(xí)需求。
OpenCV 強(qiáng)大的功能集使其成為圖像和視頻處理和分析的優(yōu)秀庫(kù),機(jī)器學(xué)習(xí)的集成使其功能更加強(qiáng)大。
更多高級(jí)示例對(duì)象跟蹤:OpenCV 提供了廣泛的對(duì)象跟蹤算法,可用于跟蹤視頻流中的對(duì)象。例如,你可以使用該cv2.TrackerKCF_create()函數(shù)創(chuàng)建一個(gè) KCF(Kernelized Correlation Filters)跟蹤器,然后使用它來跟蹤視頻流中的對(duì)象。這是一個(gè)例子:import cv2
# create the video capture object
cap = cv2.VideoCapture("video.mp4")
# get the first frame
ret, frame = cap.read()
# select the object to track
bbox = cv2.selectROI(frame, False)
# create the KCF tracker
tracker = cv2.TrackerKCF_create()
tracker.init(frame, bbox)
# start the tracking loop
while True:
# get the next frame
ret, frame = cap.read()
# update the tracker
success, bbox = tracker.update(frame)
# check if the tracking failed
if not success:
break
# draw the bounding box
cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3])), (255, 0, 0), 2)
# show the frame
cv2.imshow("Tracking", frame)
# exit if the user presses the 'q' key
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# release the video capture and close the window
cap.release()
cv2.destroyAllWindows()
光流:OpenCV 提供了廣泛的光流算法,可用于跟蹤視頻流中對(duì)象的運(yùn)動(dòng)。一種流行的算法是 Farneback 算法,可用于估計(jì)兩幀之間的光流。以下是如何使用此算法可視化視頻流中的光流的示例:import cv2
# create the video capture object
cap = cv2.VideoCapture("video.mp4")
# get the first frame
ret, frame1 = cap.read()
gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
# start the tracking loop
while True:
# get the next frame
ret, frame2 = cap.read()
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
# calculate the optical flow
flow = cv2.calcOpticalFlowFarneback(gray1, gray2, None, 0.5, 3, 15, 3, 5, 1.2, 0)
# visualize the optical flow
mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
hsv = np.zeros((gray1.shape[0], gray1.shape[1], 3), dtype=np.float32)
hsv[..., 0] = ang * 180 / np.pi / 2
hsv[..., 1] = 255
hsv[..., 2] = c
使用 OpenCV 機(jī)器學(xué)習(xí)功能的另一個(gè)示例是使用預(yù)訓(xùn)練模型進(jìn)行對(duì)象檢測(cè)。一種流行的對(duì)象檢測(cè)模型是 Single Shot MultiBox Detector (SSD),它是一種基于深度學(xué)習(xí)的模型,可以檢測(cè)圖像中的多個(gè)對(duì)象。import cv2
# read the image
image = cv2.imread("image.jpg")
# read the pre-trained model and config files
net = cv2.dnn.readNetFromCaffe("ssd.prototxt", "ssd.caffemodel")
# create a 4D blob from the image
blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0))
# set the blob as input to the model
net.setInput(blob)
# get the detections
detections = net.forward()
# loop over the detections
for i in range(detections.shape[2]):
# get the confidence of the detection
confidence = detections[0, 0, i, 2]
# filter out weak detections
if confidence > 0.5:
# get the coordinates of the detection
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
# draw the detection on the image
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
# display the image
cv2.imshow("Objects", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
在上面的示例中,我們使用cv2.dnn.readNetFromCaffe加載 SSD 模型及其配置文件,從輸入圖像創(chuàng)建一個(gè) blob,將 blob 設(shè)置為模型的輸入,運(yùn)行前向傳播以獲得檢測(cè),過濾掉弱檢測(cè),并繪制檢測(cè)在圖像上。
另一個(gè)例子是使用 OpenCV 的cv2.Tracker類來跟蹤視頻中的對(duì)象。import cv2
# Read video
cap = cv2.VideoCapture("video.mp4")
# Read the first frame
ret, frame = cap.read()
# Define the region of interest (RoI)
roi = cv2.selectROI(frame)
# Initialize the tracker
tracker = cv2.TrackerKCF_create()
tracker.init(frame, roi)
# Loop over the frames
while True:
# Read the next frame
ret, frame = cap.read()
if not ret:
break
# Update the tracker
success, roi = tracker.update(frame)
# Draw the RoI
if success:
(x, y, w, h) = [int(v) for v in roi]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Show the frame
cv2.imshow("Frame", frame)
key = c
使用 OpenCV 的另一個(gè)高級(jí)示例是使用圖像摳圖技術(shù)使圖像中的對(duì)象消失。圖像摳圖是估計(jì)圖像中每個(gè)像素的不透明度的過程,它允許你將前景對(duì)象與背景分開。
下面是如何使用 OpenCV 的cv2.createBackgroundSubtractorMOG2函數(shù)從圖像中提取前景對(duì)象并使其消失的示例:
import cv2
# Read the image
image = cv2.imread("image.jpg")
# Create the background subtractor
bgSubtractor = cv2.createBackgroundSubtractorMOG2()
# Apply the background subtractor to the image
fgMask = bgSubtractor.apply(image)
# Use a morphological operator to remove noise
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
fgMask = cv2.morphologyEx(fgMask, cv2.MORPH_CLOSE, kernel)
# Invert the mask to get the background
bgMask = cv2.bitwise_not(fgMask)
# Use the mask to extract the background and the object
bg = cv2.bitwise_and(image, image, mask=bgMask)
fg = cv2.bitwise_and(image, image, mask=fgMask)
# Set the object pixels to transparent
fg[fg > 0] = (255, 255, 255, 0)
# Combine the background and the transparent object
result = cv2.addWeighted(bg, 1, fg, 1, 0)
# Show the result
cv2.imshow("Object Disappeared", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
在這個(gè)例子中,我們使用 OpenCV 的cv2.createBackgroundSubtractorMOG2函數(shù)創(chuàng)建了一個(gè)背景減法器,然后將其應(yīng)用于圖像以提取前景對(duì)象。
然后我們使用形態(tài)學(xué)運(yùn)算符從掩模中去除噪聲。之后,我們反轉(zhuǎn)掩碼以提取背景,并使用掩碼提取背景和對(duì)象。
最后,我們將對(duì)象像素設(shè)置為透明,并將背景和透明對(duì)象組合在一起,以創(chuàng)建帶有消失對(duì)象的最終結(jié)果。
總結(jié)
OpenCV 是用于計(jì)算機(jī)視覺和機(jī)器學(xué)習(xí)任務(wù)的強(qiáng)大且廣泛使用的庫(kù)。它提供了廣泛的圖像和視頻處理工具,包括特征檢測(cè)、圖像識(shí)別、對(duì)象跟蹤和機(jī)器學(xué)習(xí)。
本文中提供的示例演示了使用 OpenCV 讀取和顯示圖像、將圖像轉(zhuǎn)換為灰度、檢測(cè)圖像中的特征以及對(duì)象檢測(cè)和圖像摳圖等任務(wù)。
OpenCV 還提供了許多基于機(jī)器學(xué)習(xí)的功能,例如使用 cv2.ml 和 cv2.dnn 模塊進(jìn)行檢測(cè)、識(shí)別和跟蹤。借助 OpenCV,開發(fā)人員可以輕松地將計(jì)算機(jī)視覺和機(jī)器學(xué)習(xí)功能集成到他們的項(xiàng)目中,并為各個(gè)行業(yè)創(chuàng)造新的解決方案。
原文標(biāo)題 : 通過實(shí)際示例學(xué)習(xí)計(jì)算機(jī)視覺和機(jī)器學(xué)習(xí)的基本技術(shù)

發(fā)表評(píng)論
請(qǐng)輸入評(píng)論內(nèi)容...
請(qǐng)輸入評(píng)論/評(píng)論長(zhǎng)度6~500個(gè)字
最新活動(dòng)更多
-
即日-6.16立即報(bào)名>> 【在線會(huì)議】Solution Talks |Computex 2025關(guān)鍵趨勢(shì)深讀
-
6月20日立即下載>> 【白皮書】精準(zhǔn)測(cè)量 安全高效——福祿克光伏行業(yè)解決方案
-
7月3日立即報(bào)名>> 【在線會(huì)議】英飛凌新一代智能照明方案賦能綠色建筑與工業(yè)互聯(lián)
-
7月22-29日立即報(bào)名>> 【線下論壇】第三屆安富利汽車生態(tài)圈峰會(huì)
-
7.30-8.1火熱報(bào)名中>> 全數(shù)會(huì)2025(第六屆)機(jī)器人及智能工廠展
-
7月31日免費(fèi)預(yù)約>> OFweek 2025具身機(jī)器人動(dòng)力電池技術(shù)應(yīng)用大會(huì)
推薦專題
- 1 AI 眼鏡讓百萬 APP「集體失業(yè)」?
- 2 大廠紛紛入局,百度、阿里、字節(jié)搶奪Agent話語權(quán)
- 3 深度報(bào)告|中國(guó)AI產(chǎn)業(yè)正在崛起成全球力量,市場(chǎng)潛力和關(guān)鍵挑戰(zhàn)有哪些?
- 4 上海跑出80億超級(jí)獨(dú)角獸:獲上市公司戰(zhàn)投,干人形機(jī)器人
- 5 國(guó)家數(shù)據(jù)局局長(zhǎng)劉烈宏調(diào)研格創(chuàng)東智
- 6 下一代入口之戰(zhàn):大廠為何紛紛押注智能體?
- 7 百億AI芯片訂單,瘋狂傾銷中東?
- 8 Robotaxi新消息密集釋放,量產(chǎn)元年誰在領(lǐng)跑?
- 9 格斗大賽出圈!人形機(jī)器人致命短板曝光:頭腦過于簡(jiǎn)單
- 10 為何全球AI巨頭都在搶?MCP協(xié)議背后的暴富玄機(jī)大公開!