訂閱
糾錯(cuò)
加入自媒體

通過(guò)實(shí)際示例學(xué)習(xí)計(jì)算機(jī)視覺(jué)和機(jī)器學(xué)習(xí)的基本技術(shù)

OpenCV 是一個(gè)開(kāi)源的計(jì)算機(jī)視覺(jué)庫(kù),廣泛應(yīng)用于計(jì)算機(jī)視覺(jué)和機(jī)器學(xué)習(xí)領(lǐng)域。它提供了廣泛的圖像和視頻處理工具,包括特征檢測(cè)、圖像識(shí)別和對(duì)象跟蹤。

在本文中,我們將了解如何使用 OpenCV 執(zhí)行各種任務(wù),重點(diǎn)是如何使用它來(lái)應(yīng)用機(jī)器學(xué)習(xí)。

首先,讓我們從安裝開(kāi)始,你需要在你的環(huán)境中安裝 OpenCV 庫(kù),你可以通過(guò)運(yùn)行以下命令來(lái)完成此操作:

pip install opencv-python

或者

conda install -c conda-forge opencv

一旦安裝了 OpenCV,就可以開(kāi)始在 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類(lèi)來(lái)檢測(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模塊來(lái)訓(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模塊來(lái)加載和使用預(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ī)視覺(jué)和機(jī)器學(xué)習(xí)任務(wù)的幾個(gè)示例。OpenCV 擁有廣泛的工具和功能,是一個(gè)強(qiáng)大的庫(kù),可供數(shù)據(jù)科學(xué)家用于滿(mǎn)足他們的計(jì)算機(jī)視覺(jué)和機(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)跟蹤器,然后使用它來(lái)跟蹤視頻流中的對(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è),過(guò)濾掉弱檢測(cè),并繪制檢測(cè)在圖像上。

另一個(gè)例子是使用 OpenCV 的cv2.Tracker類(lèi)來(lái)跟蹤視頻中的對(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è)像素的不透明度的過(guò)程,它允許你將前景對(duì)象與背景分開(kāi)。

下面是如何使用 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ī)視覺(jué)和機(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,開(kāi)發(fā)人員可以輕松地將計(jì)算機(jī)視覺(jué)和機(jī)器學(xué)習(xí)功能集成到他們的項(xiàng)目中,并為各個(gè)行業(yè)創(chuàng)造新的解決方案。

       原文標(biāo)題 : 通過(guò)實(shí)際示例學(xué)習(xí)計(jì)算機(jī)視覺(jué)和機(jī)器學(xué)習(xí)的基本技術(shù)

聲明: 本文由入駐維科號(hào)的作者撰寫(xiě),觀(guān)點(diǎn)僅代表作者本人,不代表OFweek立場(chǎng)。如有侵權(quán)或其他問(wèn)題,請(qǐng)聯(lián)系舉報(bào)。

發(fā)表評(píng)論

0條評(píng)論,0人參與

請(qǐng)輸入評(píng)論內(nèi)容...

請(qǐng)輸入評(píng)論/評(píng)論長(zhǎng)度6~500個(gè)字

您提交的評(píng)論過(guò)于頻繁,請(qǐng)輸入驗(yàn)證碼繼續(xù)

  • 看不清,點(diǎn)擊換一張  刷新

暫無(wú)評(píng)論

暫無(wú)評(píng)論

人工智能 獵頭職位 更多
掃碼關(guān)注公眾號(hào)
OFweek人工智能網(wǎng)
獲取更多精彩內(nèi)容
文章糾錯(cuò)
x
*文字標(biāo)題:
*糾錯(cuò)內(nèi)容:
聯(lián)系郵箱:
*驗(yàn) 證 碼:

粵公網(wǎng)安備 44030502002758號(hào)