I'm currently trying to work with Google's python vision library. But I'm currently stuck on how to read images from the web. So far I've got this here down below. My issue is that the contents always seem to be empty and when I check using PyCharm, it says that it only contains b''.
How can I open this image so I can use it for Google's library?
from google.cloud import vision
from google.cloud.vision import types
from urllib import request
import io
client = vision.ImageAnnotatorClient.from_service_account_json('cred.json')
url = "https://cdn.getyourguide.com/img/location_img-59-1969619245-148.jpg"
img = request.urlopen(url)
with io.open('location_img-59-1969619245-148.jpg', 'rb') as fhand:
content = fhand.read()
image = types.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description)
Do you try get image via requests library?
import requests
r = requests.get("https://cdn.getyourguide.com/img/location_img-59-1969619245-148.jpg")
o = open("location_img.jpg", "wb")
o.write(r.content)
o.close()
Related
How do I generate a qr code which when scanned opens a url? is it possible to use a library like qrcode or pyqrcode to accomplish this?
something like this :
pyq = QRCode()
pyq.generate(url="http://google.com/")
Yes you can use qrcode:
import qrcode
import qrcode.image.svg
img = qrcode.make('http://www.google.com/', image_factory=qrcode.image.svg.SvgImage)
with open('qr.svg', 'wb') as qr:
img.save(qr)
You can use google apis to create qr code without additional library:
import requests
WIDTH = 400
HEIGHT = 400
DATA = "http://www.google.com/"
image = requests.get(f"https://chart.googleapis.com/chart?chs={WIDTH}x{HEIGHT}&cht=qr&chl={DATA}")
image.raise_for_status()
with open("qr.png", "wb") as qr:
qr.write(image.content)
We need the images from the website <https://api.data.gov.sg/v1/transport/traffic-images >.But the below script download json file.But we want to download images directly .I am beginner .Thanks in advance
from threading import Timer
import time
import requests
startlog = time.time()
image_url = "https://api.data.gov.sg/v1/transport/traffic-images"
tm = 0
while True:
tm += 1
r = requests.get(image_url) # create HTTP response object
with open(str(tm)+"trafficFile.json", 'wb') as f:
f.write(r.content)
print(tm)
time.sleep(20)
This small piece of code written above will download the following image from the web. Now check your local directory(the folder where this script resides), and you will find this image.
I can't set image thumbnails for mp3 files using eyed3 module in Python.
I try next script:
import eyed3
from eyed3.id3.frames import ImageFrame
th = 'url_to_my_pic'
file = 'to_mp3_pleer/file.mp3'
audiofile = eyed3.load(file)
audiofile.initTag()
audiofile.tag.frames = ImageFrame(image_url=th)
audiofile.tag.save()
But this do nothing with thumbnails in my file.
In google no information about settings thumbnails using eyed3. How can I set it?
After several hours learning of eyeD3, googling and experimenting with file cover, I think, I have a solution for you.
You need to follow these rules:
use ID3v2.3 (not v2.4 as by default in eyeD3);
add right description for cover image (word cover);
pass image as binary;
I'll give you an example of code, which works fine on my Windows 10 (should works on other platforms as well):
import eyed3
import urllib.request
audiofile = eyed3.load("D:\\tmp\\tmp_mp3\\track_example.mp3")
audiofile.initTag(version=(2, 3, 0)) # version is important
# Other data for demonstration purpose only (from docs)
audiofile.tag.artist = "Token Entry"
audiofile.tag.album = "Free For All Comp LP"
audiofile.tag.album_artist = "Various Artists"
audiofile.tag.title = "The Edge"
# Read image from local file (for demonstration and future readers)
with open("D:\\tmp\\tmp_covers\\cover_2021-03-13.jpg", "rb") as image_file:
imagedata = image_file.read()
audiofile.tag.images.set(3, imagedata, "image/jpeg", u"cover")
audiofile.tag.save()
# Get image from the Internet
response = urllib.request.urlopen("https://example.com/your-picture-here.jpg")
imagedata = response.read()
audiofile.tag.images.set(3, imagedata, "image/jpeg", u"cover")
audiofile.tag.save()
Credits: My code is based on several pages: 1, 2, 3
I'm using the Google Cloud Vision API with Python 3, but i'm getting the error
"Cannot find reference 'Image' in types.py" when i use:
image = vision.types.Image(content=content)
I made the correct imports and the documentation tells me to use this function to get an image. Anyone can help me?
Code:
import io
import os
from google.cloud import vision
from google.cloud.vision import types
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "C:/Keys/key.json"
client = vision.ImageAnnotatorClient
path = os.path.join(os.path.dirname(__file__), "image.jpg")
with io.open(path, "rb") as image_file:
content = image_file.read()
image = types.Image(content=content)
Error Message:
Google Cloud Vision API version: 0.36.0
You should be importing like this:
from google.cloud import vision
from google.cloud.vision import types
and then you will be able to do this:
image = types.Image(content=content)
There is a full tutorial here. It works on my machine on Python3.7 perfectly fine.
I'm making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow.
I've looked at some examples (1, 2, 3), and I think I get the gist of the process, but I keep getting an error where Pillow can't read the string I gave it.
Here's what I've got so far:
import cStringIO
from PIL import Image
import base64
data = request.form
image_string = cStringIO.StringIO(base64.b64decode(data['img']))
image = Image.open(image_string)
which gives the error:
IOError: cannot identify image file <cStringIO.StringIO object at 0x10f84c7a0>
You should try something like:
from PIL import Image
from io import BytesIO
import base64
data['img'] = '''R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLl
N48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=='''
im = Image.open(BytesIO(base64.b64decode(data['img'])))
Your data['img'] string should not include the HTML tags or the parameters data:image/jpeg;base64 that are in the example JSFiddle.
I've changed the image string for an example I took from Google, just for readability purposes.
There is a metadata prefix of data:image/jpeg;base64, being included in the img field. Normally this metadata is used in a CSS or HTML data URI when embedding image data into the document or stylesheet. It is there to provide the MIME type and encoding of the embedded data to the rendering browser.
You can strip off the prefix before the base64 decode and this should result in valid image data that PIL can load (see below), but you really need to question how the metadata is being submitted to your server as normally it should not.
import re
import cStringIO
from PIL import Image
image_data = re.sub('^data:image/.+;base64,', '', data['img']).decode('base64')
image = Image.open(cStringIO.StringIO(image_data))
Sorry for necromancy, but none of the answers worked completely for me. Here is code working on Python 3.6 and Flask 0.13.
Server:
from flask import Flask, jsonify, request
from io import BytesIO
from web import app
import base64
import re
import json
from PIL import Image
#app.route('/process_image', methods=['post'])
def process_image():
image_data = re.sub('^data:image/.+;base64,', '', request.form['data'])
im = Image.open(BytesIO(base64.b64decode(image_data)))
return json.dumps({'result': 'success'}), 200, {'ContentType': 'application/json'}
Client JS:
// file comes from file input
var reader = new FileReader();
reader.onloadend = function () {
var fileName = file.name;
$.post('/process_image', { data: reader.result, name: fileName });
};
reader.readAsDataURL(file);