下载图片

  1. import os
  2. os.makedirs('./image/', exist_ok=True)
  3. IMAGE_URL = "http://image.nationalgeographic.com.cn/2017/1122/20171122113404332.jpg"
  4. def urllib_download():
  5. from urllib.request import urlretrieve
  6. urlretrieve(IMAGE_URL, './image/img1.png')
  7. def request_download():
  8. import requests
  9. r = requests.get(IMAGE_URL)
  10. with open('./image/img2.png', 'wb') as f:
  11. f.write(r.content)
  12. def chunk_download():
  13. import requests
  14. r = requests.get(IMAGE_URL, stream=True)
  15. with open('./image/img3.png', 'wb') as f:
  16. for chunk in r.iter_content(chunk_size=32):
  17. f.write(chunk)
  18. urllib_download()
  19. print('download img1')
  20. request_download()
  21. print('download img2')
  22. chunk_download()
  23. print('download img3')

读取URL图片并转为RGB

推荐方法二

方法一 urllib和cv2

  1. import numpy as np
  2. import urllib
  3. import cv2
  4. def url_to_image(url):
  5. # download the image, convert it to a NumPy array, and then read
  6. # it into OpenCV format
  7. resp = urllib.urlopen(url)
  8. image = np.asarray(bytearray(resp.read()), dtype="uint8")
  9. image = cv2.imdecode(image, cv2.IMREAD_COLOR)
  10. # return the image
  11. return
  12. urls = ["https://x.png", "https://x.png"]
  13. for url in urls:
  14. print "downloading %s" % (url)
  15. image = url_to_image(url)
  16. cv2.imshow("Image", image)
  17. cv2.waitKey(0)

如果担心图片可能不存在或者出错,也可以使用:

  1. import io
  2. import urllib.request
  3. from PIL import Image
  4. url = 'https://cdn.wccftech.com/wp-content/uploads/2017/11/windows-10-iphone-1480x897-86x60.png'
  5. with urllib.request.urlopen(url) as f:
  6. b = io.BytesIO(f.read())
  7. im = Image.open(b)
  8. im.save('out.png')

方法二 requests和PIL

  1. import requests
  2. response = requests.get(_image_url)
  3. if response.status_code == 200:
  4. _image = Image.open(BytesIO(response.content))
  5. _image = _image.resize((224,224))
  6. _image = _image.tobytes() # 转为tfrecrod可存的格式

如果需要接着存入tfrecord,一般不需要这么复杂,tensorflow有自己的图片解码tf.image.decode_jpeg()方法。

  1. image_feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[_image]))
  2. example = tf.train.Example(
  3. features=tf.train.Features(feature={
  4. 'label': label_feature,
  5. 'text': text_feature,
  6. 'image': image_feature}))

参考

  • https://blog.csdn.net/qq_34504481/article/details/79716106

    base64 -> .jpg

    ```python import base64 imgdata = base64.b64decode(imgstring) filename = ‘some_image.jpg’ # I assume you have a way of picking unique filenames with open(filename, ‘wb’) as f: f.write(imgdata)

    f gets closed when you exit the with statement

    Now save the value of filename to your database

读取图片,并转换为base64编码,存储为string

image_path = ‘http://xxx.jpg‘ with open(image, ‘rb’) as f: image = f.read() image_base64 = str(base64.b64encode(image), encoding=’utf-8’) ```