Python 圖像識別的十個經(jīng)典算法
圖像識別是計算機視覺領(lǐng)域的一個重要分支,它涉及從圖像中提取信息并進行分類或識別。Python 作為一門強大的編程語言,在圖像識別方面有著廣泛的應用。今天,我們就來聊聊 Python 圖像識別的 10 個經(jīng)典算法,并通過實際代碼示例來幫助大家更好地理解和應用這些算法。
1. 直方圖均衡化(Histogram Equalization)
直方圖均衡化是一種常用的圖像增強技術(shù),可以改善圖像的對比度。
import cv2
import matplotlib.pyplot as plt
# 讀取圖像
image = cv2.imread('example.jpg', 0) # 以灰度模式讀取圖像
# 應用直方圖均衡化
equalized_image = cv2.equalizeHist(image)
# 顯示原圖和處理后的圖像
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(1, 2, 2)
plt.title('Equalized Image')
plt.imshow(equalized_image, cmap='gray')
plt.show()
2. Canny 邊緣檢測
Canny 邊緣檢測是一種多級邊緣檢測算法,能夠檢測出圖像中的邊緣。
import cv2
import matplotlib.pyplot as plt
# 讀取圖像
image = cv2.imread('example.jpg', 0) # 以灰度模式讀取圖像
# 應用 Canny 邊緣檢測
edges = cv2.Canny(image, 100, 200)
# 顯示原圖和邊緣檢測結(jié)果
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(1, 2, 2)
plt.title('Edges')
plt.imshow(edges, cmap='gray')
plt.show()
3. Hough 變換
Hough 變換用于檢測圖像中的直線和圓等幾何形狀。
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 讀取圖像
image = cv2.imread('example.jpg', 0) # 以灰度模式讀取圖像
# 應用 Canny 邊緣檢測
edges = cv2.Canny(image, 50, 150)
# 應用 Hough 變換檢測直線
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10)
# 繪制檢測到的直線
line_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(line_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 顯示原圖和檢測結(jié)果
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(1, 2, 2)
plt.title('Detected Lines')
plt.imshow(line_image)
plt.show()
4. SIFT 特征檢測
SIFT(Scale-Invariant Feature Transform)是一種用于圖像特征檢測和描述的算法。
import cv2
import matplotlib.pyplot as plt
# 讀取圖像
image = cv2.imread('example.jpg', 0) # 以灰度模式讀取圖像
# 創(chuàng)建 SIFT 對象
sift = cv2.SIFT_create()
# 檢測關(guān)鍵點和描述符
keypoints, descriptors = sift.detectAndCompute(image, None)
# 繪制關(guān)鍵點
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# 顯示原圖和關(guān)鍵點
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(1, 2, 2)
plt.title('Image with Keypoints')
plt.imshow(image_with_keypoints, cmap='gray')
plt.show()
5. SURF 特征檢測
SURF(Speeded-Up Robust Features)是 SIFT 的一種快速版本。
import cv2
import matplotlib.pyplot as plt
# 讀取圖像
image = cv2.imread('example.jpg', 0) # 以灰度模式讀取圖像
# 創(chuàng)建 SURF 對象
surf = cv2.xfeatures2d.SURF_create(400)
# 檢測關(guān)鍵點和描述符
keypoints, descriptors = surf.detectAndCompute(image, None)
# 繪制關(guān)鍵點
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# 顯示原圖和關(guān)鍵點
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(1, 2, 2)
plt.title('Image with Keypoints')
plt.imshow(image_with_keypoints, cmap='gray')
plt.show()
6. ORB 特征檢測
ORB(Oriented FAST and Rotated BRIEF)是一種高效的特征檢測和描述算法。
import cv2
import matplotlib.pyplot as plt
# 讀取圖像
image = cv2.imread('example.jpg', 0) # 以灰度模式讀取圖像
# 創(chuàng)建 ORB 對象
orb = cv2.ORB_create()
# 檢測關(guān)鍵點和描述符
keypoints, descriptors = orb.detectAndCompute(image, None)
# 繪制關(guān)鍵點
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# 顯示原圖和關(guān)鍵點
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(1, 2, 2)
plt.title('Image with Keypoints')
plt.imshow(image_with_keypoints, cmap='gray')
plt.show()
7. K-Means 聚類
K-Means 是一種常用的聚類算法,可以用于圖像分割。
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 讀取圖像
image = cv2.imread('example.jpg')
# 將圖像轉(zhuǎn)換為二維數(shù)組
Z = image.reshape((-1, 3))
# 將數(shù)據(jù)類型轉(zhuǎn)換為 float32
Z = np.float32(Z)
# 定義 K-Means 參數(shù)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 3
ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# 將中心值轉(zhuǎn)換為 uint8
center = np.uint8(center)
# 將標簽映射回圖像
res = center[label.flatten()]
segmented_image = res.reshape((image.shape))
# 顯示原圖和分割后的圖像
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.subplot(1, 2, 2)
plt.title('Segmented Image')
plt.imshow(cv2.cvtColor(segmented_image, cv2.COLOR_BGR2RGB))
plt.show()
8. 主成分分析(PCA)
PCA 是一種常用的數(shù)據(jù)降維技術(shù),可以用于圖像壓縮。
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 讀取圖像
image = cv2.imread('example.jpg', 0) # 以灰度模式讀取圖像
# 將圖像轉(zhuǎn)換為二維數(shù)組
Z = image.reshape((-1, 1))
# 將數(shù)據(jù)類型轉(zhuǎn)換為 float32
Z = np.float32(Z)
# 應用 PCA
mean, eigenvectors = cv2.PCACompute(Z, mean=None)
# 選擇前 n 個主成分
n_components = 50
projected = cv2.PCAProject(Z, mean, eigenvectors[:, :n_components])
# 重構(gòu)圖像
reconstructed = cv2.PCABackProject(projected, mean, eigenvectors[:, :n_components])
reconstructed_image = reconstructed.reshape(image.shape).astype(np.uint8)
# 顯示原圖和重構(gòu)后的圖像
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.subplot(1, 2, 2)
plt.title('Reconstructed Image')
plt.imshow(reconstructed_image, cmap='gray')
plt.show()
9. 卷積神經(jīng)網(wǎng)絡(CNN)
CNN 是深度學習中的一種常用模型,特別適用于圖像識別任務。
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
# 加載數(shù)據(jù)集
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
# 數(shù)據(jù)預處理
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
# 構(gòu)建 CNN 模型
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
# 編譯模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 訓練模型
history = model.fit(train_images, train_labels, epochs=5, batch_size=64, validation_split=0.2)
# 評估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')
# 繪制訓練過程中的損失和準確率
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.legend()
plt.show()
10. YOLOv5 目標檢測
YOLO(You Only Look Once)是一種實時目標檢測算法,YOLOv5 是其最新版本。
import torch
from PIL import Image
import matplotlib.pyplot as plt
# 加載預訓練的 YOLOv5 模型
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
# 讀取圖像
image = Image.open('example.jpg')
# 進行目標檢測
results = model(image)
# 顯示檢測結(jié)果
results.show()
實戰(zhàn)案例:手寫數(shù)字識別
假設我們需要構(gòu)建一個手寫數(shù)字識別系統(tǒng),可以使用上面提到的 CNN 模型來實現(xiàn)。我們將使用 MNIST 數(shù)據(jù)集進行訓練和測試。
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
# 加載數(shù)據(jù)集
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
# 數(shù)據(jù)預處理
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
# 構(gòu)建 CNN 模型
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
# 編譯模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 訓練模型
history = model.fit(train_images, train_labels, epochs=5, batch_size=64, validation_split=0.2)
# 評估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')
# 繪制訓練過程中的損失和準確率
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.legend()
plt.show()
本文介紹了 Python 圖像識別的 10 個經(jīng)典算法,包括直方圖均衡化、Canny 邊緣檢測、Hough 變換、SIFT 特征檢測、SURF 特征檢測、ORB 特征檢測、K-Means 聚類、主成分分析(PCA)、卷積神經(jīng)網(wǎng)絡(CNN)和 YOLOv5 目標檢測。通過實際代碼示例,我們展示了如何應用這些算法來處理圖像。