帮我写一个基于pytorch的提取人脸特征的代码,并在gpu(cuda)上加速
时间: 2023-04-04 08:01:13 浏览: 115
好的,以下是基于 PyTorch 的提取人脸特征的代码,并在 GPU(CUDA)上加速:
```python
import torch
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
# 加载预训练的 ResNet50 模型
model = models.resnet50(pretrained=True)
# 将模型移动到 GPU 上
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# 设置模型为评估模式
model.eval()
# 定义预处理函数
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[.485, .456, .406], std=[.229, .224, .225])
])
# 加载图像并进行预处理
img = Image.open("path/to/image.jpg")
img_tensor = preprocess(img)
img_tensor = img_tensor.unsqueeze()
img_tensor = img_tensor.to(device)
# 提取人脸特征
with torch.no_grad():
features = model(img_tensor)
# 将特征转换为 numpy 数组
features = features.cpu().numpy()
print(features)
```
希望这个代码能够帮到你!
阅读全文