grcnn单张图片预测代码
时间: 2025-08-20 22:51:30 浏览: 3
### GRCNN 单张图片预测实现代码
为了展示如何使用GRCNN模型对单张图片进行预测,下面提供了一个Python代码示例。此代码假设已经有一个预训练好的GRCNN模型,并且该模型可以加载并用于推理模式下处理新输入的图像。
```python
import torch
from torchvision import transforms
from PIL import Image
import numpy as np
def load_image(image_path):
"""Load and preprocess an image."""
img = Image.open(image_path).convert('RGB')
transform = transforms.Compose([
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
img_tensor = transform(img)
return img_tensor.unsqueeze(0)
def predict_single_image(model, device, image_path):
"""Predict segmentation mask for a single input image using the trained model."""
model.eval()
with torch.no_grad():
tensor_img = load_image(image_path).to(device)
output = model(tensor_img)['out']
pred_mask = torch.argmax(output.squeeze(), dim=0).detach().cpu().numpy()
return pred_mask
if __name__ == "__main__":
# Load your pretrained GR-CNN model here.
grcnn_model = ... # Placeholder for loading or defining the actual GR-CNN architecture
# Set up GPU/CPU environment
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
# Move model to appropriate device (GPU/CPU).
grcnn_model.to(device)
test_image_path = 'path_to_your_test_image.jpg'
prediction_result = predict_single_image(grcnn_model, device, test_image_path)
print(f"The shape of predicted mask is {prediction_result.shape}")
```
上述代码实现了从读取一张测试图片到通过已有的GR-CNN模型得到其对应的分割掩码的过程[^1]。注意,在实际应用中需要替换`grcnn_model = ...`这行代码中的省略号部分为具体的模型定义或加载语句。
阅读全文
相关推荐




















