I want to do a practice that consists of capturing webs in jpg, but it did not just work (I am newbie), this is the code I use.
import numpy as np
import urllib
import cv2
def url_to_image("http://www.hereiputweb.com"):
resp = urllib.urlopen("http://www.hereiputweb.com")
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
The code I got it from a manual but it gives me fault in the line:
def url_to_image("http://www.hereiputweb.com"):
I think I indicated the web incorrectly, very far I should not be .. tried several forms but nothing .. what do I do wrong?
regards
There is a really brief tutorial (https://docs.python.org/3/tutorial/).
The relevant part would be https://docs.python.org/3/tutorial/controlflow.html#defining-functions
So, you should define your function as follows:
def url_to_image(url):
resp = urllib.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
I have not checked the implementation works ;)
Then you can use your function:
url = "http://www.hereiputweb.com"
my_image = url_to_image(url)
The problem is not with your implementation, it's with your URL!
This method require a functioning URL that returns an image. The URL you're using is not an image.
Try using an URL of an image (e.g: some URLs that end with .jpg) and it shall work!
Remember that the URL must be on-line!
Related
I can do this OK both in js and php but not in python. I'm trying to pull a thumbnail image from google books api into a python variable.
The text objects are fine eg
newTitle = (parsed_json['items'][0]['volumeInfo']['title'])
isbn10 = (parsed_json['items'][0]['volumeInfo']['industryIdentifiers'][1]['identifier'])
isbn13 = (parsed_json['items'][0]['volumeInfo']['industryIdentifiers'][0]['identifier'])
The image is supplied in the api as follows. (if you put the http// url into a browser you see the image):
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
I have tried the simple:
myImage = (parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
which doesn't work.
I have installed pillow to provide image management:
from PIL import Image
img = Image.open("parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail]") or
img = Image.open(parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
which doesn't work. I have tried more complex arrangements:
from PIL import Image
import requests
from io import BytesIO
response = requests.get(parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
img = Image.open(BytesIO(response.content))
but nothing seems to work. I have tried many other variations on these attempts. I have also, unsuccessfully tried to load the text that points to the thumbnail to try another route. I am confident that the "['items'][0]['volumeInfo']['imageLinks'][thumbnail]" is correct though my only way of testing whether the variable is properly loaded is to save it or if the line of code isn't working.
I didn't have problems downloading and opening the image.
I have use the following code
import requests
from PIL import Image
image_url = "https://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api"
r = requests.get(image_url)
with open("demo_image",'wb') as f:
f.write(r.content)
img = Image.open("demo_image")
import requests
def linkFetch():
url = "https://api.unsplash.com/photos/random/?client_id=MyAccessKey"
response = requests.get(url)
data = response.json()["urls"]["raw"]
return data
def imageFetch(data):
print(data)
imageFetch(linkFetch())
Here my code runs and fetches a url for an image but how can I automatically open the photo in small window. the linkFetch() function actually gets the image link and I want imageFetch() to actually open the photo. I'm new to using apis so any help will be useful. I already tried using another request.get() but I may have used it incorrectly. Other solutions seem to want to download the image indefinitely where I want to just open it.
Note: MyAccessKey replaces my actual key
You have to first get the image data by sending a request then pass it to the pillow package to display the image.
from io import BytesIO
from PIL import Image
import requests
img_url = imageFetch(linkFetch())
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
img.show()
I am trying to use cv2 and pyzbar for real time reading of QR codes from an IP camera.
This works:
os.system("wget --quiet http://user:password#url -O file.jpg")
image = cv2.imread("file.jpg")
barcodes = pyzbar.decode(image)
But it's clearly inefficient - much better to imread the url directly. But I can't work out how to do that with basic authentication. Would really appreciate some help.
(There have been a number of similar questions but I can't find any that have been answered!)
thanks
Dan
or there's this alternative simple solution that doesn't involve streaming the video:
from requests.auth import HTTPBasicAuth
import numpy as np
resp = requests.get(url, auth=(user, password))
image = np.asarray(bytearray(resp.content), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
Hope it helps other people!
this may help you
import numpy as np
import urllib.request as rq
import cv2
from matplotlib import pyplot as plt
# load image from url
def urlToImage(url):
# download image,convert to a NumPy array,and read it into opencv
resp = rq.urlopen(url)
img = np.asarray(bytearray(resp.read()),dtype="uint8")
img = cv2.imdecode(img,cv2.IMREAD_COLOR)
#return the image
return img
img = urlToImage("https://www.pyimagesearch.com/wp-content/uploads/2015/01/google_logo.png")
plt.imshow(img)
Thanks all - but turns out there is a nice simple answer:
cap=cv2.VideoCapture("http://user:password#url")
_, image=cap.read()
barcodes = pyzbar.decode(image)
I am trying to read an img from a url. My code works when the img is coded jpeg, but, when It's .svg for example, the function imdecode from openCV just don't work. Here it is the code:
url_response = urllib.urlopen("https://upload.wikimedia.org/wikipedia/commons/a/ac/BanderaEstepa.svg")
img_array = array(bytearray(url_response.read()), dtype=uint8)
img_url = cv2.imdecode(img_array, 1)
Need help please. Thanks in advance.
How do I serve a dynamically generated image in Django?
I have an html tag
<html>
...
<img src="images/dynamic_chart.png" />
...
</html>
linked up to this request handler, which creates an in-memory image
def chart(request):
img = Image.new("RGB", (300,300), "#FFFFFF")
data = [(i,randint(100,200)) for i in range(0,300,10)]
draw = ImageDraw.Draw(img)
draw.polygon(data, fill="#000000")
# now what?
return HttpResponse(output)
I also plan to change the requests to AJAX, and add some sort of caching mechanism, but my understanding is that wouldn't affect this part of the solution.
I assume you're using PIL (Python Imaging Library). You need to replace your last line with (for example, if you want to serve a PNG image):
response = HttpResponse(mimetype="image/png")
img.save(response, "PNG")
return response
See here for more information.
I'm relatively new to Django myself. I haven't been able to find anything in Django itself, but I have stumbled upon a project on Google Code that may be of some help to you:
django-dynamic-media-serve
I was looking for a solution of the same problem
And for me this simple approach worked fine:
from django.http import FileResponse
def dyn_view(request):
response = FileResponse(open("image.png","rb"))
return response
Another way is to use BytesIO. BytesIO is like a buffer. So one can save the image (which is fast enough than writing to disk) in that buffer.
from PIL import Image, ImageDraw
import io
def chart(request):
img = Image.new('RGB', (240, 240), color=(250,160,170))
draw = ImageDraw.Draw(img)
draw.text((20, 40), 'some_text')
buff = io.BytesIO()
img.save(buff, 'jpeg')
return HttpResponse(buff.getvalue(), content_type='image/jpeg')