下载图片
import osos.makedirs('./image/', exist_ok=True)IMAGE_URL = "http://image.nationalgeographic.com.cn/2017/1122/20171122113404332.jpg"def urllib_download():from urllib.request import urlretrieveurlretrieve(IMAGE_URL, './image/img1.png')def request_download():import requestsr = requests.get(IMAGE_URL)with open('./image/img2.png', 'wb') as f:f.write(r.content)def chunk_download():import requestsr = requests.get(IMAGE_URL, stream=True)with open('./image/img3.png', 'wb') as f:for chunk in r.iter_content(chunk_size=32):f.write(chunk)urllib_download()print('download img1')request_download()print('download img2')chunk_download()print('download img3')
读取URL图片并转为RGB
方法一 urllib和cv2
import numpy as npimport urllibimport cv2def url_to_image(url):# download the image, convert it to a NumPy array, and then read# it into OpenCV formatresp = urllib.urlopen(url)image = np.asarray(bytearray(resp.read()), dtype="uint8")image = cv2.imdecode(image, cv2.IMREAD_COLOR)# return the imagereturnurls = ["https://x.png", "https://x.png"]for url in urls:print "downloading %s" % (url)image = url_to_image(url)cv2.imshow("Image", image)cv2.waitKey(0)
如果担心图片可能不存在或者出错,也可以使用:
import ioimport urllib.requestfrom PIL import Imageurl = 'https://cdn.wccftech.com/wp-content/uploads/2017/11/windows-10-iphone-1480x897-86x60.png'with urllib.request.urlopen(url) as f:b = io.BytesIO(f.read())im = Image.open(b)im.save('out.png')
方法二 requests和PIL
import requestsresponse = requests.get(_image_url)if response.status_code == 200:_image = Image.open(BytesIO(response.content))_image = _image.resize((224,224))_image = _image.tobytes() # 转为tfrecrod可存的格式
如果需要接着存入tfrecord,一般不需要这么复杂,tensorflow有自己的图片解码tf.image.decode_jpeg()方法。
image_feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[_image]))example = tf.train.Example(features=tf.train.Features(feature={'label': label_feature,'text': text_feature,'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’) ```
