import requests
import cv2
frame=cv2.imread('C:\\Users\\aaa\\Downloads\\abc.jpg')
url = 'https://app.nanonets.com/api/v2/ObjectDetection/Model/4729a79f-ab19-4c1b-8fe9'
data = {'file': open('C:\\Users\\aaa\\Downloads\\abc.jpg', 'rb')}
response = requests.post(url, auth=requests.auth.HTTPBasicAuth('S5zsN-yFZJxRH9tMwsaHUCxJg3dZaDWj', ''), files=data)
print (type(response))
print(response)
I uploaded an image for object detection. I got the response like this.
{"message":"Success","result":[{"message":"Success","input":"abc.jpg","prediction":[{"label":"car","xmin":411,"ymin":332,"xmax":585,"ymax":462,"score":0.99097943},{"label":"car","xmin":496,"ymin":170,"xmax":592,"ymax":248,"score":0.96399206},{"label":"car","xmin":223,"ymin":147,"xmax":294,"ymax":202,"score":0.9383388},{"label":"car","xmin":164,"ymin":130,"xmax":230,"ymax":175,"score":0.8968652},{"label":"car","xmin":448,"ymin":489,"xmax":623,"ymax":540,"score":0.8311123}],"page":0,"request_file_id":"5a8549f1-fb2c-487a-83b5-234608b3168b","filepath":"uploadedfiles/4729a79f-ab19-fac0fb807e6d/PredictionImages/53207.jpeg"}]}
I want to make a box in the image with the given coordinates.
import requests
import cv2
import math
from PIL import Image, ImageDraw
import json
frame=cv2.imread('C:\Users\aaa\Downloads\abc.jpg')
url = 'https://app.nanonets.com/api/v2/ObjectDetection/Model/4729a79f-ab19-4c1b-8fe9'
data = {'file': open('C:\Users\aaa\Downloads\abc.jpg', 'rb')}
response = requests.post(url, auth=requests.auth.HTTPBasicAuth('S5zsN-yFZJxRH9tMwsaHUCxJg3dZaDWj', ''), files=data)
predictions = json.loads(response.text)['result'][0]['prediction']
img = Image.open('C:\Users\aaa\Downloads\abc.jpg')
img1 = ImageDraw.Draw(img)
for prediction in predictions:
shape = [(prediction['xmin'], prediction['ymin']), (prediction['xmax'], prediction['ymax'])]
img1.rectangle(shape, fill ="# ffff33", outline ="red")
img.show()
Related
I'm trying to detect width and height of an image before saving it to the database and S3. The image is in bytes.
This is an example of an image before saved to Django ImageField:
NOTE: I don't want to use ImageFields height_field and width_field as it slows down the server tremendously for some reason so I want to do it manually.
The image is downloaded using requests:
def download_image(url):
r = requests.get(url, stream=True)
r.raw.decode_content = True
return r.content
To get the width/height of an image from a binary string, you would have to try to parse the binary string with an image library. The easiest one for the job would be pillow.
import requests
from PIL import Image
import io
def download_image(url):
r = requests.get(url, stream=True)
r.raw.decode_content = True
return r.content
image_url = "https://picsum.photos/seed/picsum/300/200"
image_data = download_image(image_url)
image = Image.open(io.BytesIO(image_data))
width = image.width
height = image.height
print(f'width: {width}, height: {height}')
width: 300, height: 200
I am trying to convert image to JSON file and POST it with REST API by using MLFLow. Below you can see my code. I got an error like "cannot reshape array of size 535500 into shape (1,4096)". Can you please help me. Thank you in advance.
import json
import cv2
import requests
import base64
import numpy as np
from PIL import Image
data = np.asarray(Image.open('Dataset/test2/dog_PNG50348.png').convert('LA'))
data = data.reshape((1, 64*64))
columns = [f"col_{c}" for c in range(0, data[0].shape[0])]
dct = {"columns": columns, "data": [data[0].tolist()]}
print(json.dumps(dct, indent=2) + "\n")
#print(data)
headers = {'Content-Type': 'application/json'}
request_uri = 'http://127.0.0.1:5000/invocations'
if __name__ == '__main__':
try:
response = requests.post(request_uri, data=json.dumps(dct,indent=2)+"\n", headers=headers)
print(response.content)
print('done!!!')
except Exception as ex:
raise (ex)
I have a python code for downloading images from "www.image-net.org" for haar cascade training. Basically it checks each image urls and download the images.
import urllib2
import cv2
import numpy as np
import os
import urllib
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def store_raw_images():
pos_images_link = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n04154340'
pos_image_urls = urllib2.urlopen(pos_images_link).read().decode()
if not os.path.exists('pos'):
os.makedirs('pos')
pic_num = 1
for i in pos_image_urls.split('\n'):
try:
print(i)
urllib.urlretrieve(i, "pos/"+str(pic_num)+".jpg")
img = cv2.imread("pos/"+str(pic_num)+".jpg",cv2.IMREAD_GRAYSCALE)
# should be larger than samples / pos pic (so we can place our image on it)
resized_image = cv2.resize(img, (100, 100))
cv2.imwrite("pos/"+str(pic_num)+".jpg",resized_image)
pic_num += 1
except Exception as e:
print(str(e))
store_raw_images()
I copy paste the url link to download in "pos_images_link", but the code only checks the urls of 5 images then the code stops running with a message in the terminal:
"terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr: __pos (which is 140) > this->size() (which is 0)"
, i am using opencv 3.1.0 and python 2.7.12
The follows worked in python 3 with opencv
from urllib.request import Request, urlretrieve
import cv2
import numpy as np
import os
import urllib
import sys
def store_raw_images():
url = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n04154340'
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
urls = response.read().decode('utf-8')
if not os.path.exists('pos'):
os.makedirs('pos')
pic_num = 1
for i in urls.split('\n'):
try:
print(i)
urlretrieve(i, "pos/"+str(pic_num)+".jpg")
img = cv2.imread("pos/"+str(pic_num)+".jpg",cv2.IMREAD_GRAYSCALE)
# should be larger than samples / pos pic (so we can place our image on it)
resized_image = cv2.resize(img, (100, 100))
cv2.imwrite("pos/"+str(pic_num)+".jpg",resized_image)
pic_num += 1
except Exception as e:
print(str(e))
store_raw_images()
I have my bot working by now, but the thing is it can only send text. I have seen in the Bot API there are functions to send photos, videos... but I can't get it to work. Someone has achieved it? I'm using python source code from yukuku/telebot
elif text == '/image':
img = Image.new('RGB', (512, 512))
base = random.randint(0, 16777216)
pixels = [base+i*j for i in range(512) for j in range(512)] # generate sample image
img.putdata(pixels)
output = StringIO.StringIO()
img.save(output, 'JPEG')
reply(img=output.getvalue())
When I change the code, nothing happened.
img = Image.open('image.png')
img.show()
Please help me. I need the correct code. Sorry for my bad English.
I have included two functions, one is good for sending local images, the other one is good for sending remote images.
def sendImage():
url = "https://api.telegram.org/bot<Token>/sendPhoto";
files = {'photo': open('/path/to/img.jpg', 'rb')}
data = {'chat_id' : "YOUR_CHAT_ID"}
r= requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
def sendImageRemoteFile(img_url):
url = "https://api.telegram.org/bot<Token>/sendPhoto";
remote_image = requests.get(img_url)
photo = io.BytesIO(remote_image.content)
photo.name = 'img.png'
files = {'photo': photo}
data = {'chat_id' : "YOUR_CHAT_ID"}
r= requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
The solution is
elif 'Hi' in text:
reply(img=urllib2.urlopen('img url').read())
or
if text == 'help':
reply(img=urllib2.urlopen('img url').read())
Before sending the photo, you have to do output.seek(0) to put the cursor back to the beginning of the file, else it will be read as zero
I understand the question. Here's the answer:
def sendImageFromUrl(url):
#this tweak added if request image failed
headers = {'user-agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'}
response = requests.get(url, headers=headers)
#response = requests.get(url)
output = StringIO(response.content)
img = Image.open(output)
img.save(output, 'JPEG')
resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
('chat_id', str(chat_id)),
('caption', 'Your Caption'),
], [
('photo', 'image.jpg', output.getvalue()),
])
Make sure your server does have python module: requests.
You can download here: https://pypi.python.org/pypi/requests#downloads
And put in your application like this
/myapp/app.yaml
/myapp/main.py
/myapp/requests/packages/
/myapp/requests/__init__.py
/myapp/requests/adapters.py
etc...
Credit: https://stackoverflow.com/a/17128168/1097372
Put in main.py after line 10
import requests
from StringIO import StringIO
I am using requests to get the image from remote URL. Since the images will always be 16x16, I want to convert them to base64, so that I can embed them later to use in HTML img tag.
import requests
import base64
response = requests.get(url).content
print(response)
b = base64.b64encode(response)
src = "data:image/png;base64," + b
The output for response is:
response = b'GIF89a\x80\x00\x80\x00\xc4\x1f\x00\xff\xff\xff\x00\x00\x00\xff\x00\x00\xff\x88\x88"""\xffff\...
The HTML part is:
<img src="{{src}}"/>
But the image is not displayed.
How can I properly base-64 encode the response?
I think it's just
import base64
import requests
response = requests.get(url)
uri = ("data:" +
response.headers['Content-Type'] + ";" +
"base64," + base64.b64encode(response.content))
Assuming content-type is set.
This worked for me:
import base64
import requests
response = requests.get(url)
uri = ("data:" +
response.headers['Content-Type'] + ";" +
"base64," + base64.b64encode(response.content).decode("utf-8"))
You may use the base64 package.
import requests
import base64
response = requests.get(url).content
print(response)
b64response = base64.b64encode(response)
print b64response
Here's my code to send/receive images over Http requests, encoded with base64
Send Request:
# Read Image
image_data = cv2.imread(image_path)
# Convert numpy array To PIL image
pil_detection_img = Image.fromarray(cv2.cvtColor(img_detections, cv2.COLOR_BGR2RGB))
# Convert PIL image to bytes
buffered_detection = BytesIO()
# Save Buffered Bytes
pil_detection_img.save(buffered_detection, format='PNG')
# Base 64 encode bytes data
# result : bytes
base64_detection = base64.b64encode(buffered_detection.getvalue())
# Decode this bytes to text
# result : string (utf-8)
base64_detection = base64_detection.decode('utf-8')
base64_plate = base64_plate.decode('utf-8')
data = {
"cam_id": "10415",
"detecion_image": base64_detection,
}
Recieve Request
content = request.json
encoded_image = content['image']
decoded_image = base64.b64decode(encoded_image)
out_image = open('image_name', 'wb')
out_image.write(decoded_image)