一、OpenCV:介紹和安裝
OpenCV是一款開源的計算機視覺庫,它提供了許多數字圖像處理和計算機視覺算法,使得開發人員能夠輕鬆構建視覺應用程序。
安裝OpenCV最簡單的方法是使用pip安裝。在命令提示符下,鍵入以下命令:
pip install opencv-python
安裝完成後,您可以導入cv2模塊作為opencv在Python中的接口模塊。
import cv2
二、圖像處理
OpenCV可以幫助我們對圖像進行各種處理。
1. 讀取圖像
要讀取圖像,我們需要使用cv2.imread()函數。
import cv2
# Load an image
img = cv2.imread('image.jpg')
# Show the image
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. 圖像操作
通過cv2中提供的函數,我們可以對圖像進行各種操作,如圖像旋轉、縮放、裁剪等。
3. 圖像濾波
濾波可以幫助我們去除圖像中的噪聲或不需要的部分。
import cv2
# Load an image
img = cv2.imread('image.jpg')
# Add some noise to the image
noise_img = cv2.addNoise(img)
# Apply median filter
median_img = cv2.medianBlur(noise_img, 5)
# Show the original image and the filtered image
cv2.imshow('Original Image', img)
cv2.imshow('Median Filtered Image', median_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
三、對象檢測
1. 人臉檢測
OpenCV提供了haar級聯分類器來檢測人臉。
import cv2
# Load the classifier
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the image
img = cv2.imread('image.jpg')
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# Draw bounding boxes around the faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Show the image
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. 物體檢測
除了人臉檢測,OpenCV還提供了其他物體檢測器,如車輛、眼睛、車牌等。
四、視頻處理
除了圖像處理,OpenCV還提供了許多功能來處理視頻流,例如從攝像機獲取實時視頻,將視頻保存到文件,以及對視頻進行操作和編輯。
1. 實時視頻捕獲
要從攝像機獲取實時視頻,我們需要使用cv2.VideoCapture()函數。
import cv2
# Capture video from camera
cap = cv2.VideoCapture(0)
while True:
# Read frame from camera
ret, frame = cap.read()
# Display the frame
cv2.imshow('Frame', frame)
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
# Release the camera and destroy all windows
cap.release()
cv2.destroyAllWindows()
2. 視頻編輯
除了從攝像機獲取實時視頻之外,OpenCV還可以讀取視頻文件並進行編輯。
import cv2
# Read video file
cap = cv2.VideoCapture('video.mp4')
# Get video frame dimensions
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Create video writer object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (width, height))
# Loop through video frames
while cap.isOpened():
# Read the frame
ret, frame = cap.read()
# If the frame is read correctly, process it
if ret == True:
# Flip the frame
frame = cv2.flip(frame, 0)
# Write the flipped frame to the output video file
out.write(frame)
# Display the flipped frame
cv2.imshow('Frame', frame)
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
else:
break
# Release the video capture and writer objects, and destroy all windows
cap.release()
out.release()
cv2.destroyAllWindows()
原創文章,作者:IVHL,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/131780.html