url to numpy, tensor

JoongHyun·2023년 7월 25일
0
import torch
import torchvision.transforms as transforms
from PIL import Image
import requests
from io import BytesIO
import numpy as np
# Replace 'your_image_url' with the URL of the image you want to convert

# Step 1: Download the image from the URL
url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Honeycrisp-Apple.jpg/2269px-Honeycrisp-Apple.jpg'
response = requests.get(url)
image = Image.open(BytesIO(response.content))

# Step 2: Convert the image to a PyTorch tensor
# First, convert the image to RGB if it has an alpha channel (RGBA)
if image.mode == 'RGBA':
    image = image.convert('RGB')

# Next, convert the PIL image to a PyTorch tensor
transform = transforms.ToTensor()
tensor_image = transform(image)
tensor_image.shape

img = tensor_image.numpy()
image_for_imshow = np.transpose(img ,(1, 2, 0))
print(img.shape)
tensor_image = torch.tensor(img)
print(tensor_image.shape)

import matplotlib.pyplot as plt

plt.imshow(image_for_imshow)

profile
AI Engineer 도전

0개의 댓글

관련 채용 정보