Programming

파이썬의 URL에서 이미지 데이터를 어떻게 읽습니까?

procodes 2020. 6. 8. 21:49
반응형

파이썬의 URL에서 이미지 데이터를 어떻게 읽습니까?


로컬 파일을 다룰 때 내가하려고하는 것은 매우 간단하지만 원격 URL 로이 작업을 수행하려고하면 문제가 발생합니다.

기본적으로 URL에서 가져온 파일에서 PIL 이미지 객체를 만들려고합니다. 물론 항상 URL을 가져 와서 임시 파일에 저장 한 다음 이미지 객체로 열 수는 있지만 매우 비효율적입니다.

내가 가진 것은 다음과 같습니다.

Image.open(urlopen(url))

seek()사용할 수 없다는 불평이 나기 때문에 이것을 시도했습니다.

Image.open(urlopen(url).read())

그러나 그것은 작동하지 않았습니다. 이 작업을 수행하는 더 좋은 방법이 있습니까, 아니면 이런 종류의 작업을 허용하는 방법으로 임시 파일에 쓰는 중입니까?


Python3에서는 StringIO 및 cStringIO 모듈이 사라졌습니다.

Python3에서는 다음을 사용해야합니다.

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

StringIO를 사용해보십시오.

import urllib, cStringIO

file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)

요청 라이브러리를 사용합니다. 더 강력 해 보입니다.

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

버전 2.8.0부터 Pillow를 사용하는 사용자는 다음을 수행 할 수 있습니다.

from PIL import Image
import urllib2

im = Image.open(urllib2.urlopen(url))

또는 사용하는 경우 requests:

from PIL import Image
import requests

im = Image.open(requests.get(url, stream=True).raw)

참고 문헌 :


StringIO읽은 문자열을 파일과 같은 객체로 바꾸려면 사용하십시오 .

from StringIO import StringIO
import urllib

Image.open(StringIO(urllib.requests.urlopen(url).read()))

sklearn / numpy 사후 처리 (즉, 딥 러닝)를 수행하는 사람들은 PIL 객체를 np.array ()로 래핑 할 수 있습니다. 이렇게하면 내가했던 것처럼 Google에 저장하지 않아도됩니다.

from PIL import Image
import requests
import numpy as np
from StringIO import StringIO

response = requests.get(url)
img = np.array(Image.open(StringIO(response.content)))

파이썬 3

from urllib.request import urlopen
from PIL import Image

img = Image.open(urlopen(url))
img

Jupyter Notebook 및 IPython

import IPython
url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
IPython.display.Image(url, width = 250)

다른 방법과 달리이 방법은 for 루프에서도 작동합니다!


크롬에서 이미지를 선택하고 마우스 오른쪽 버튼으로 클릭 한 다음을 클릭 Copy image address하고 str변수 ( my_url)에 붙여 이미지를 읽으십시오.

import shutil
import requests

my_url = 'https://www.washingtonian.com/wp-content/uploads/2017/06/6-30-17-goat-yoga-congressional-cemetery-1-994x559.jpg'
response = requests.get(my_url, stream=True)
with open('my_image.png', 'wb') as file:
    shutil.copyfileobj(response.raw, file)
del response

열어 봐;

from PIL import Image

img = Image.open('my_image.png')
img.show()

The arguably recommended way to do image input/output these days is to use the dedicated package ImageIO. Image data can be read directly from a URL with one simple line of code:

from imageio import imread
image = imread('https://cdn.sstatic.net/Sites/stackoverflow/img/logo.png')

Many answers on this page predate the release of that package and therefore do not mention it. ImageIO started out as component of the Scikit-Image toolkit. It supports a number of scientific formats on top of the ones provided by the popular image-processing library PILlow. It wraps it all in a clean API solely focused on image input/output. In fact, SciPy removed its own image reader/writer in favor of ImageIO.

참고URL : https://stackoverflow.com/questions/7391945/how-do-i-read-image-data-from-a-url-in-python

반응형