Skip to content

计算机视觉

计算机视觉概述

什么是计算机视觉

计算机视觉是人工智能的一个分支,使计算机能够理解和解释图像和视频。

计算机视觉任务

  • 图像分类
  • 对象检测
  • 图像分割
  • 人脸识别
  • 图像生成

图像处理基础

python
import cv2
import numpy as np

# 读取图像
image = cv2.imread('image.jpg')

# 转换为灰度
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 边缘检测
edges = cv2.Canny(gray, 100, 200)

# 保存图像
cv2.imwrite('edges.jpg', edges)

使用预训练模型

python
from transformers import pipeline

# 创建图像分类器
classifier = pipeline("image-classification")

# 分类图像
result = classifier("cat.jpg")
print(result)

目标检测

python
from transformers import DetrImageProcessor, DetrForObjectDetection
import torch

# 加载模型
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")

# 处理图像
inputs = processor(images=image, return_tensors="pt")

# 推理
outputs = model(**inputs)

# 处理结果
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes)[0]

图像生成

python
from diffusers import StableDiffusionPipeline

# 加载模型
pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")

# 生成图像
prompt = "a photo of a cat in a hat"
image = pipe(prompt).images[0]

# 保存图像
image.save("cat_in_hat.png")

上一章: 自然语言处理

基于 VitePress 构建