自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python 圖像識別的十個經(jīng)典算法

開發(fā)
本文介紹了 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 目標檢測。通過實際代碼示例,我們展示了如何應用這些算法來處理圖像。

責任編輯:趙寧寧 來源: 手把手PythonAI編程
相關(guān)推薦

2025-03-25 08:30:00

OpenCV計算機視覺圖像識別

2024-08-26 14:57:36

2024-05-30 12:27:42

Python代碼

2022-10-20 09:33:35

2023-06-27 15:50:23

Python圖像處理

2022-02-25 11:07:19

計算機圖像識別深度學習

2019-08-13 11:39:29

編程語言技術(shù)Python

2010-09-08 14:35:22

CSS

2021-04-09 20:49:44

PythonOCR圖像

2021-10-22 09:09:27

Python圖像處理工具編程語言

2021-02-03 17:15:35

圖像識別AI人工智能

2018-04-24 10:45:00

Python人工智能圖像識別

2024-07-18 15:08:27

2024-06-18 08:16:49

2022-10-11 23:35:28

神經(jīng)網(wǎng)絡VGGNetAlexNet

2021-07-22 08:16:02

人工智能AI

2023-11-24 09:26:29

Java圖像

2023-06-13 06:51:09

Spark機器學習回歸

2023-11-22 19:24:36

2024-01-30 00:40:10

點贊
收藏

51CTO技術(shù)棧公眾號