人工智能在计算机视觉中的应用
人工智能在计算机视觉领域的应用日益广泛,从图像识别到目标检测再到图像生成,都有着重要的作用。下面将通过几个常见的示例来说明人工智能在计算机视觉中的应用:
1.图像分类
图像分类是计算机视觉中最基本的任务之一,其目标是将图像分配到预定义的类别中。人工智能模型可以通过学习大量标记好的图像来识别不同类别的图像。
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
import numpy as np
# 加载预训练的 MobileNetV2 模型
model = MobileNetV2(weights='imagenet')
# 加载图像并预处理
img_path = 'example_image.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
# 使用模型进行预测
preds = model.predict(x)
# 将预测结果解码为人类可读的标签
decoded_preds = decode_predictions(preds, top=3)[0]
# 打印预测结果
print('Predictions:')
for i, (imagenet_id, label, score) in enumerate(decoded_preds):
print(f'{i + 1}: {label} ({score:.2f})')
2. 目标检测
目标检测是识别图像中特定对象位置的任务,它不仅能够识别图像中的对象,还能够定位它们在图像中的位置。
import cv2
# 加载预训练的目标检测模型
net = cv2.dnn.readNetFromTensorflow('frozen_inference_graph.pb', 'ssd_mobilenet_v2_coco.pbtxt')
# 加载图像
image = cv2.imread('example_image.jpg')
h, w = image.shape[:2]
# 将图像转换为 blob
blob = cv2.dnn.blobFromImage(image, size=(300, 300), swapRB=True, crop=False)
net.setInput(blob)
# 运行模型进行目标检测
detections = net.forward()
# 显示检测结果
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
class_id = int(detections[0, 0, i, 1])
label = classes[class_id]
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype('int')
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
cv2.putText(image, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('Output', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
3. 图像生成
除了识别现有的图像外,人工智能还可以生成新的图像,例如生成艺术作品、虚拟人物等。
import tensorflow as tf
from tensorflow.keras.applications import VGG19
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from tensorflow.keras.applications.vgg19 import preprocess_input, decode_predictions
import numpy as np
# 加载预训练的 VGG19 模型
model = VGG19(weights='imagenet')
# 准备输入图像
img_path = 'example_image.jpg'
img = load_img(img_path, target_size=(224, 224))
img_array = img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
# 生成图像
preds = model.predict(img_array)
# 将预测结果解码为人类可读的标签
decoded_preds = decode_predictions(preds, top=3)[0]
# 打印预测结果
print('Predictions:')
for i, (imagenet_id, label, score) in enumerate(decoded_preds):
print(f'{i + 1}: {label} ({score:.2f})')