Iam using kairos api for face recognition .Iam trying to enroll an image.The documentation here says it also accepts base64 encode photos.So I have encoded the image using base 64 and I get the following error
{"Errors":[{"ErrCode":5000,"Message":"an invalid image was sent must be jpg or p
ng format"}]}
I have used the following python code for sending the requests
import cv2
import requests
import base64
import json
image=cv2.imread('Face-images/Subject 9.jpg')
encoded_string =base64.b64encode(image)
payload2= {"image":encoded_string ,"subject_id":"Abhishek","gallery_name":"MyGallery"}
headers={'Content-Type':'application/json','app_id':'app_id','app_key':'app_key'}
r = requests.post('https://api.kairos.com/enroll',headers=headers,data=json.dumps(payload2),verify=False)
print r.text
Any help would be appreciated
Don't encode your photos. Probably they accept it, but its harder to pass. Check this solution:
import requests
files = {"image": (filename,open(location+'/'+filename,"rb"))}
payload= {"subject_id":"Abhishek",
"gallery_name":"MyGallery"}
headers={'Content-Type':'application/json',
'app_id':'app_id',
'app_key':'app_key'}
response = requests.post('https://api.kairos.com/enroll',headers=headers,data=payload,files=files,verify=False)
print response.text
I found the answer to the problem. You can try reading the image not using cv2, but as simple raw binary. cv2 reads it into a numpy array and you are encoding a numpy array. Reading like a simple file works for me, like below
with open ('messi.jpg','rb') as imgFh:
img = imgFh.read()
Try this.
import cv2
import requests
import base64
import json
encoded_string = base64.b64encode(open("Face-images/Subject 9.jpg",
'r').read())
payload_dict = {
"image":encoded_string,
"subject_id": "Abhishek",
"gallery_name": "MyGallery"
}
payload = json.dumps(payload_dict)
headers={
'Content-Type':'application/json',
'app_id':'app_id',
'app_key':'app_key'
}
request = Request('https://api.kairos.com/enroll', data=payload,
headers=headers)
response_body = urlopen(request).read()
print(response_body)
Related
When I am trying to upload my base64 encoded image I receive a 413 Client Error: Request Entity Too Large for url
When clicking the error link that the Spotify API provides in the terminal it says:
{
"error": {
"status": 401,
"message": "No token provided"
}
}
Here is my code:
(Client Secret,ID and PlaylistID are not real by the way)
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import base64 #for playlist cover image
playlist_id = "P1a6gzPL0Xg51or8rfirrsr19f6Pi1e4cfzX101fcf"
def change_playlist_cover_image():
cv = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="7122ce01c646449565965a18c4597779",
client_secret="7f8bcfd7b7e5310bbcc5706b634f4c37",
redirect_uri="http://127.0.0.1:9090",
scope = "ugc-image-upload"))
image = open('lilmini.jpg', 'rb')
image_read = image.read()
image_64_encode = base64.b64encode(image_read)
cv.playlist_upload_cover_image(playlist_id,image_64_encode)
change_playlist_cover_image()
I already tried different versions of encoding the image since I thougt I messed up that part.
Also I thought maybe the authorization with SpotifyOAuth is not working properly and tried a few different things there but nothing worked in the end.
You forgot to add all the required scopes. Also, the image size must be under 256 KB.
Here is the modified code:
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import base64 # for playlist cover image
playlist_id = "P1a6gzPL0Xg51or8rfirrsr19f6Pi1e4cfzX101fcf"
def change_playlist_cover_image():
cv = spotipy.Spotify(
auth_manager=SpotifyOAuth(
client_id="7122ce01c646449565965a18c4597779",
client_secret="7f8bcfd7b7e5310bbcc5706b634f4c37",
redirect_uri="http://127.0.0.1:9090",
scope="ugc-image-upload playlist-modify-public playlist-modify-private", # added missing scopes
)
)
with open("lilmini.jpg", "rb") as image_file: # opening file safely
image_64_encode = base64.b64encode(image_file.read())
if len(image_64_encode) > 256000: # check if image is too big
print("Image is too big: ", len(image_64_encode))
else:
cv.playlist_upload_cover_image(playlist_id, image_64_encode)
print("Image added.")
change_playlist_cover_image()
I'm trying to extract texts from CAPTCHA pictures. The idea is to use lxml to get the image data from the form. The image data is prepended with a header that defines the data type. I'm guessing the CAPTCHA picture is a PNG image encoded in Base64. The image data is decoded from Base64 into the initial binary format. Meanwhile PIL wraps the binary data with BytesIO before it is passed to the PIL.Image class.
Here is the snippet's first section.
import lxml.html
import urllib.request as urllib2
import pprint
import http.cookiejar as cookielib
from io import BytesIO
import lxml.html
from PIL import Image
import pytesseract
def parse_form(html):
tree = lxml.html.fromstring(html)
data = {}
for e in tree.cssselect('form input'):
if e.get('name'):
data[e.get('name')] = e.get('value')
return data
REGISTER_URL = 'http://tracuunnt.gdt.gov.vn/tcnnt/mstdn.jsp'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
html = opener.open(REGISTER_URL).read()
form = parse_form(html)
Here, this function raises OSError: cannot identify image file <_io.BytesIO object at 0x08B3B060>:
def get_captcha(html):
tree = lxml.html.fromstring(html)
img_data = tree.cssselect('div img')[0].get('src')
img_data = img_data.partition('-')[-1]
binary_img_data = img_data.decode('base64')
file_like = BytesIO(binary_img_data)
img = Image.open(file_like)
return img
img = get_captcha(html)
I'm suspecting that it is the binary_img_data variable. I've tried to read up on decoding, encoding, PIL doc, and binary data on how to PIL can possibly read a web-based image i.e CAPTCHA but got nothing helpful.
To decode the base64 string, try the following:
from base64 import b64decode
binary_img_data = b64decode(img_data)
The method your code uses (img_data.decode('base64')) was valid in Python 2, but will not work in Python 3.
Totally overlooked the solution at the beginning. PILLOW couldn't read the image in binary data with that logic so I simply called the content of request.get() that bears the image's binary form and called Pillow to open it on the fly with BytesIO().
import lxml.html
import urllib.request as urllib2
from io import BytesIO
import lxml.html
from PIL import Image
img_data = tree.cssselect('div img')[0].get('src')
img_link = 'http://tracuunnt.gdt.gov.vn'+ img_data
response = requests.get(img_link)
img = Image.open(BytesIO(response.content))
Problematic
I have a PIL Image and i want to convert it to a bytes array. I can't save the image on my hard disk so i can't use the default open(file_path, 'rb') function.
What i tried
To overturn this problem i'm trying to use the io library doing this :
buf = io.BytesIO()
image.save(buf, format='JPEG')
b_image = buf.getvalue()
Considering image as a functional PIL Image.
the "b_image" will be used as argument for the Microsoft Azure cognitives services function read_in_stream()
If we look in the documentation, we can see that this function image argument have to be :
image
xref:Generator
Required
An image stream.
Documentation available here
The issue
When i execute it i got the error :
File "C:...\envs\trainer\lib\site-packages\msrest\service_client.py", line 137, in stream_upload
chunk = data.read(self.config.connection.data_block_size)
AttributeError: 'bytes' object has no attribute 'read'
There is no error in the client authentification or at another point because when i give as parameter an image imported with this line :
image = open("./1.jpg", 'rb')
Everything is working correctly..
Sources
I also saw this post that explains exactly what i want to do but in my case it's not working. Any idea would be appreciated.
When we use the method read_in_stream, we need to provide a stream. But the code BytesIO.getvalue will return the content of the stream as string or bytes. So please update code as below
buf = io.BytesIO()
image.save(buf, format='JPEG')
computervision_client.read_in_stream(buf)
For more details, please refer to here
Update
Regarding the issue, I suggest you use rest API to implement your need.
import io
import requests
from PIL import Image
import time
url = "{your endpoint}/vision/v3.1/read/analyze"
key = ''
headers = {
'Ocp-Apim-Subscription-Key': key,
'Content-Type': 'application/octet-stream'
}
// process image
...
with io.BytesIO() as buf:
im.save(buf, 'jpeg')
response = requests.request(
"POST", url, headers=headers, data=buf.getvalue())
# get result
while True:
res = requests.request(
"GET", response.headers['Operation-Location'], headers=headers)
status = res.json()['status']
if status == 'succeeded':
print(res.json()['analyzeResult'])
break
time.sleep(1)
I have an existing url of an image,
I want to download the image straight to a variable (no need to actually download it, maybe get it from a response?
The end result will be "download an image into a BytesIO() variable".
What is the correct way to do so?
You can use requests:
import requests
from io import BytesIO
response = requests.get(url)
image_data = BytesIO(response.content)
Note this works in Python 3.X
You could also just duck-type the underlying urllib3 response object, which is for many practical purposes the same interface as a BytesIO anyway.
Example using the PNG of your identicon:
>>> url = "https://www.gravatar.com/avatar/33f6d36c91913f4b6776525a09d131d0?s=32&d=identicon&r=PG&f=1"
>>> resp = requests.get(url, stream=True)
>>> resp.raw
<urllib3.response.HTTPResponse at 0x7fffe88927b8>
>>> resp.raw.read()
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\tpHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95+\x0e\x1b\x00\x00\x00\xf6IDATX\x85\xedW1\x12\xc20\x0c\x93\xb9\x0em\xc3\xeb\x98)3?b\x87\x9d\xcf\xd1\xa4[\xcd\x06\xd89bz\xe50C\xb4\xe5\xda\xaa\xba\xc8Qlbf\xc6\x0b\xd2.\xa1\x84\xfe\xda\x17\x9f\xa7!\x01\xf1\xfd\xf3\xee\xdc\x81\xb6\xf4Xo\x8al?#\x15\xd0h\xcf\xdbS\x0b\nO\x8f^\xfd\x02\x80\xe98\x81\xa3(\x1b\x81\xfe"k\x84G\xf9\xeet\x98\xa4\x00M#\x81\xb2\x9f\n\xc2\xc8\xc5"\xcb\xf8\n\\\xc0\x1fX\xe0. \xb7\xc0\xd82\xed\xf1b\x04\x08\x0b\xddw\xa0\n }\x17\xe8s\xbe\xd6\xf34\xc8\x9c\xd1|Y\x11.=\xe7&\x0c.w\x0b\xaa\x80*\xc0]\x00\xc5\xbd\xbc\xdcWg\xbd\x01\x9d3\xcdW\xcf\xfc\x07\xd09\xe3n\x81\xbb\x80<\x8aG.\xf6\x04V\xdfo\xcd\r\xfa[\xf7\x1d\xa8\x02h\xbe\xcd\xb2\x1fP};\x82\\Z9\x91\xcd\r\xcas=w4V\x13\xba4\'\xac~B\xcf\x1d\xee\x16\xb8\x0b\xb8\x03\x91\x99Z?\x1eYA8\x00\x00\x00\x00IEND\xaeB`\x82'
I'm currently developing a small script to take screenshots and upload them to imgur using Python.
The code looks like this:
import time
import os
import ImageGrab
import urllib
import urllib2
time.sleep(1)
shot = ImageGrab.grab()
dir = os.path.join(r'C:\SAMPLE\PATH', 'Screen ' + time.strftime(r'%Y-%m-%d %H-%M-%S') + '.png')
shot.save(dir)
data = urllib.urlencode({"key":'MY_API_KEY', "image":urllib.quote(open(dir,'rb').read().encode("base64"))})
site = urllib2.Request("http://imgur.com/api/upload.json", data)
s = urllib2.urlopen(site)
print s.read()
I get a response from imgur but when I open the link I get a blank image (though its resolution is correct). I think the base64 encoding method may be off but I'm at a loss.
You should use b64encode from the base64 module. I don't know why, but it gives different results:
from base64 import b64encode
(...)
data = urllib.urlencode({"key":'MY_API_KEY', "image":urllib.quote(b64encode(open(dir,'rb').read()))})