Код: Выделить всё
import torch
from torchvision import models, transforms
from PIL import Image
import requests
from io import BytesIO
import os
import json
# Specify the path to the locally downloaded ResNet50 weights file
weights_path = '/Users/rishiamin/Downloads/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' # Update with the actual path
# Load the pre-trained ResNet model
model = models.resnet50()
model.eval()
# Load the weights from the local file
model.load_state_dict(torch.load(weights_path))
# Define the transformation for the input image
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# Load labels for ImageNet classes from a local file
labels_path = '/Users/rishiamin/Desktop/imagenet-simple-labels.json'
with open(labels_path, 'r') as f:
classes = json.load(f)
# Function to predict image
def predict_image_url(image_url):
try:
# Load image from URL with SSL certificate verification enabled
response = requests.get(image_url, verify=True)
response.raise_for_status()
img = Image.open(BytesIO(response.content))
# Preprocess the image
img = preprocess(img)
img = img.unsqueeze(0) # Add batch dimension
# Make predictions
with torch.no_grad():
output = model(img)
# Get the predicted class
_, predicted_idx = torch.max(output, 1)
predicted_label = classes[predicted_idx.item()]
print(f"Predicted Label: {predicted_label}")
except requests.RequestException as e:
print(f"Error loading image from URL: {e}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
#Switch between http and https if link doesn't work
image_url = 'http://cdn.britannica.com/18/137318-050-29F7072E/rooster-Rhode-Island-Red-roosters-chicken-domestication.jpg'
predict_image_url(image_url)
Файл «/Users/rishiamin/PycharmProjects/Image Recognition/main.py», строка 17, в
модели. load_state_dict(torch.load(weights_path))
Файл "/Users/rishiamin/Library/Python/3.8/lib/python/site-packages/torch/serialization.py", строка 1040, в загрузке
return _legacy_load(opened_file, map_location, Pickle_module, **pickle_load_args)
Файл "/Users/rishiamin/Library/Python/3.8/lib/python/site-packages/torch/serialization.py", строка 1258, в _legacy_load
magic_number = Pickle_module.load(f, **pickle_load_args)
_pickle.UnpicklingError: неверный ключ загрузки, 'H'.
Я ожидал получить его словесный ответ из сети изображений, простые метки того, что изображено на картинке, которую я предоставил.
Подробнее здесь: https://stackoverflow.com/questions/784 ... ng-pytorch