偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

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

開(kāi)發(fā)
本文介紹了 Python 圖像識(shí)別的十個(gè)經(jīng)典算法,通過(guò)實(shí)際代碼示例,我們展示了如何應(yīng)用這些算法來(lái)處理圖像。

圖像識(shí)別是計(jì)算機(jī)視覺(jué)領(lǐng)域的一個(gè)重要分支,它涉及從圖像中提取信息并進(jìn)行分類或識(shí)別。Python 作為一門強(qiáng)大的編程語(yǔ)言,在圖像識(shí)別方面有著廣泛的應(yīng)用。今天,我們就來(lái)聊聊 Python 圖像識(shí)別的 10 個(gè)經(jīng)典算法,并通過(guò)實(shí)際代碼示例來(lái)幫助大家更好地理解和應(yīng)用這些算法。

1. 直方圖均衡化(Histogram Equalization)

直方圖均衡化是一種常用的圖像增強(qiáng)技術(shù),可以改善圖像的對(duì)比度。

import cv2
import matplotlib.pyplot as plt

# 讀取圖像
image = cv2.imread('example.jpg', 0)  # 以灰度模式讀取圖像

# 應(yīng)用直方圖均衡化
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 邊緣檢測(cè)

Canny 邊緣檢測(cè)是一種多級(jí)邊緣檢測(cè)算法,能夠檢測(cè)出圖像中的邊緣。

import cv2
import matplotlib.pyplot as plt

# 讀取圖像
image = cv2.imread('example.jpg', 0)  # 以灰度模式讀取圖像

# 應(yīng)用 Canny 邊緣檢測(cè)
edges = cv2.Canny(image, 100, 200)

# 顯示原圖和邊緣檢測(cè)結(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 變換用于檢測(cè)圖像中的直線和圓等幾何形狀。

import cv2
import numpy as np
import matplotlib.pyplot as plt

# 讀取圖像
image = cv2.imread('example.jpg', 0)  # 以灰度模式讀取圖像

# 應(yīng)用 Canny 邊緣檢測(cè)
edges = cv2.Canny(image, 50, 150)

# 應(yīng)用 Hough 變換檢測(cè)直線
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10)

# 繪制檢測(cè)到的直線
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)

# 顯示原圖和檢測(cè)結(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 特征檢測(cè)

SIFT(Scale-Invariant Feature Transform)是一種用于圖像特征檢測(cè)和描述的算法。

import cv2
import matplotlib.pyplot as plt

# 讀取圖像
image = cv2.imread('example.jpg', 0)  # 以灰度模式讀取圖像

# 創(chuàng)建 SIFT 對(duì)象
sift = cv2.SIFT_create()

# 檢測(cè)關(guān)鍵點(diǎn)和描述符
keypoints, descriptors = sift.detectAndCompute(image, None)

# 繪制關(guān)鍵點(diǎn)
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# 顯示原圖和關(guān)鍵點(diǎ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 特征檢測(cè)

SURF(Speeded-Up Robust Features)是 SIFT 的一種快速版本。

import cv2
import matplotlib.pyplot as plt

# 讀取圖像
image = cv2.imread('example.jpg', 0)  # 以灰度模式讀取圖像

# 創(chuàng)建 SURF 對(duì)象
surf = cv2.xfeatures2d.SURF_create(400)

# 檢測(cè)關(guān)鍵點(diǎn)和描述符
keypoints, descriptors = surf.detectAndCompute(image, None)

# 繪制關(guān)鍵點(diǎn)
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# 顯示原圖和關(guān)鍵點(diǎ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 特征檢測(cè)

ORB(Oriented FAST and Rotated BRIEF)是一種高效的特征檢測(cè)和描述算法。

import cv2
import matplotlib.pyplot as plt

# 讀取圖像
image = cv2.imread('example.jpg', 0)  # 以灰度模式讀取圖像

# 創(chuàng)建 ORB 對(duì)象
orb = cv2.ORB_create()

# 檢測(cè)關(guān)鍵點(diǎn)和描述符
keypoints, descriptors = orb.detectAndCompute(image, None)

# 繪制關(guān)鍵點(diǎn)
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# 顯示原圖和關(guān)鍵點(diǎ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)

# 將標(biāo)簽映射回圖像
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)

# 應(yīng)用 PCA
mean, eigenvectors = cv2.PCACompute(Z, mean=None)

# 選擇前 n 個(gè)主成分
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)絡(luò)(CNN)

CNN 是深度學(xué)習(xí)中的一種常用模型,特別適用于圖像識(shí)別任務(wù)。

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ù)預(yù)處理
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'])

# 訓(xùn)練模型
history = model.fit(train_images, train_labels, epochs=5, batch_size=64, validation_split=0.2)

# 評(píng)估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')

# 繪制訓(xùn)練過(guò)程中的損失和準(zhǔn)確率
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 目標(biāo)檢測(cè)

YOLO(You Only Look Once)是一種實(shí)時(shí)目標(biāo)檢測(cè)算法,YOLOv5 是其最新版本。

import torch
from PIL import Image
import matplotlib.pyplot as plt

# 加載預(yù)訓(xùn)練的 YOLOv5 模型
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')

# 讀取圖像
image = Image.open('example.jpg')

# 進(jìn)行目標(biāo)檢測(cè)
results = model(image)

# 顯示檢測(cè)結(jié)果
results.show()

實(shí)戰(zhàn)案例:手寫(xiě)數(shù)字識(shí)別

假設(shè)我們需要構(gòu)建一個(gè)手寫(xiě)數(shù)字識(shí)別系統(tǒng),可以使用上面提到的 CNN 模型來(lái)實(shí)現(xiàn)。我們將使用 MNIST 數(shù)據(jù)集進(jìn)行訓(xùn)練和測(cè)試。

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ù)預(yù)處理
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'])

# 訓(xùn)練模型
history = model.fit(train_images, train_labels, epochs=5, batch_size=64, validation_split=0.2)

# 評(píng)估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')

# 繪制訓(xùn)練過(guò)程中的損失和準(zhǔn)確率
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 圖像識(shí)別的 10 個(gè)經(jīng)典算法,包括直方圖均衡化、Canny 邊緣檢測(cè)、Hough 變換、SIFT 特征檢測(cè)、SURF 特征檢測(cè)、ORB 特征檢測(cè)、K-Means 聚類、主成分分析(PCA)、卷積神經(jīng)網(wǎng)絡(luò)(CNN)和 YOLOv5 目標(biāo)檢測(cè)。通過(guò)實(shí)際代碼示例,我們展示了如何應(yīng)用這些算法來(lái)處理圖像。

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

2025-03-25 08:30:00

OpenCV計(jì)算機(jī)視覺(jué)圖像識(shí)別

2024-08-26 14:57:36

2024-05-30 12:27:42

Python代碼

2023-06-27 15:50:23

Python圖像處理

2010-09-08 14:35:22

CSS

2022-10-20 09:33:35

2022-02-25 11:07:19

計(jì)算機(jī)圖像識(shí)別深度學(xué)習(xí)

2019-08-13 11:39:29

編程語(yǔ)言技術(shù)Python

2021-10-22 09:09:27

Python圖像處理工具編程語(yǔ)言

2021-04-09 20:49:44

PythonOCR圖像

2024-07-18 15:08:27

2018-04-24 10:45:00

Python人工智能圖像識(shí)別

2021-02-03 17:15:35

圖像識(shí)別AI人工智能

2024-12-03 14:33:42

Python遞歸編程

2024-01-30 00:40:10

2022-10-11 23:35:28

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

2024-06-18 08:16:49

2023-06-13 06:51:09

Spark機(jī)器學(xué)習(xí)回歸

2023-11-22 19:24:36

2021-12-02 14:55:44

Python項(xiàng)目編程語(yǔ)言
點(diǎn)贊
收藏

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