1from PIL import Image
2import numpy as np
3import torch
4
5def predict_image(model, image):
6 # Preprocess the image
7 if isinstance(image, Image.Image):
8 image = image.resize((28, 28)).convert('L')
9 image = np.array(image).astype('float32') / 255.0
10 elif isinstance(image, np.ndarray):
11 if image.shape != (28, 28):
12 image = Image.fromarray(image).resize((28, 28)).convert('L')
13 image = np.array(image).astype('float32') / 255.0
14 else:
15 raise ValueError("Image must be a PIL Image or NumPy array.")
16
17 image = image.reshape(1, 1, 28, 28)
18 image_tensor = torch.tensor(image).to(device)
19
20 # Get prediction
21 model.eval()
22 with torch.no_grad():
23 output = model(image_tensor)
24 _, predicted = torch.max(output.data, 1)
25 return 'cat' if predicted.item() == 0 else 'dog'
26
27# Example usage
28image = Image.open('path/to/your/image.png')
29prediction = predict_image(model, image)
30print(prediction)