I am trying to display photos from NASA API but I only get the piece of this photo.
I tried to change the geometry of the window app but I still have the same problem.
Also, I tried to resize the image but I am getting errors.
import requests
from pprint import PrettyPrinter
import json
import datetime
from tkinter import *
from PIL import Image, ImageTk
from urllib.request import urlopen
root = Tk()
root.geometry("800x500")
root.title("Nasa photo of a day")
pp = PrettyPrinter()
api_key = 'PRIVATE KEY'
today_date = datetime.date.today()
URL_APOD = "https://api.nasa.gov/planetary/apod"
date = today_date
params = {
'api_key': api_key,
'date': date,
'hd': 'True'
}
response_image = requests.get(URL_APOD, params=params)
json_data = json.loads(response_image.text)
image_url = json_data['hdurl']
print(image_url)
imageUrl = image_url
u = urlopen(imageUrl)
raw_data = u.read()
u.close()
nasa_img = ImageTk.PhotoImage(data=raw_data)
my_label1 = Label(image=nasa_img)
my_label1.pack()
root.mainloop()
This is how it looks like
And this is how is should looks like
You can pass the result of urlopen(...) to PIL.Image() to fetch the image and then resize the image as below:
with urlopen(imageUrl) as fd:
# fetch the image from URL and resize it to desired size
image = Image.open(fd).resize((500,500))
nasa_img = ImageTk.PhotoImage(image)
my_label1 = Label(image=nasa_img)
my_label1.pack()
Related
It's a loop understanding problem, I'm new to Tkinter and I don't know how the images are updated
°°°PROBLEM°°°
It is about making a program that captures images of the esp32-cam module and can visualize and use them with the urllib and Opencv libraries, in addition to displaying the images in Tkinter to make a user interface
The image updates correctly but scrolls down as shown in the images
I would like you to help me with the problem and how to anchor it where I want, use the function .place (x = 0, y = 0) in and out of the loop but the image was not updating
°°°IMAGES°°°
starting the program, the image is centered in the Tkinter window, that's fine.
first capture
when the image is refreshed at 500 milliseconds, the image is scrolled down "infinitely", as shown in the following image:
second capture
#Python v3.8.4
import tkinter as *
from PIL import Image, ImageTk
import cv2
import numpy as np
import urllib.request
url='http://192.168.0.24/picture'
delay = 1000
imgtk = [None]
def loopCapture():
imgResponse = urllib.request.urlopen (url)
imgNp =np.array(bytearray(imgResponse.read()),dtype=np.uint8)
image = cv2.imdecode (imgNp, -1)
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
im = Image.fromarray(img)
imgtk[0] = ImageTk.PhotoImage(image = im)
capture = Label(root, image = imgtk[0]).pack()
root.after(delay, loopCapture)
root = Tk()
root.geometry("1200x700")
loopCapture()
root.mainloop()
I just needed to learn more about the tkinter library, but if anyone comes across the same question, here is the code:
capture when running the program.
from PIL import Image, ImageTk
import urllib.request
import tkinter as tk
import numpy as np
import cv2
# esp32-cam url
urlCam ='http://192.168.0.24/picture'
panel = None
root = None
def loopCamera():
imgResponse = urllib.request.urlopen (urlCam)
imgNp = np.array(bytearray(imgResponse.read()),dtype=np.uint8)
image = cv2.imdecode (imgNp, -1)
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image = im)
panel.configure(image = imgtk)
panel.image = imgtk
panel.after(5, loopCamera)
root = tk.Tk()
root.title('car-vision')
root.geometry('1000x600')
panel = tk.Label(root)
panel.pack()
loopCamera()
root.mainloop()
I have a bunch of images in my S3 bucket folder.
I have a list of keys from S3 (img_list) and I can read and display the images:
key = img_list[0]
bucket = s3_resource.Bucket(bucket_name)
img = bucket.Object(key).get().get('Body').read()
I have a function for that:
def image_from_s3(bucket, key):
bucket = s3_resource.Bucket(bucket)
image = bucket.Object(key)
img_data = image.get().get('Body').read()
return Image.open(io.BytesIO(img_data))
Now what I want is to read the image using OpenCV but I am getting an error:
key = img_list[0]
bucket = s3_resource.Bucket(bucket_name)
img = bucket.Object(key).get().get('Body').read()
cv2.imread(img)
SystemError Traceback (most recent call last)
<ipython-input-13-9561b5237a85> in <module>
2 bucket = s3_resource.Bucket(bucket_name)
3 img = bucket.Object(key).get().get('Body').read()
----> 4 cv2.imread(img)
SystemError: <built-in function imread> returned NULL without setting an error
Please advise how to read it in the right way?
Sorry, I got it wrong in the comments. This code sets up a PNG file in a memory buffer to simulate what you get from S3:
#!/usr/bin/env python3
from PIL import Image, ImageDraw
import cv2
# Create new solid red image and save to disk as PNG
im = Image.new('RGB', (640, 480), (255, 0, 0))
im.save('image.png')
# Slurp entire contents, raw and uninterpreted, from disk to memory
with open('image.png', 'rb') as f:
raw = f.read()
# "raw" should now be very similar to what you get from your S3 bucket
Now, all I need is this:
nparray = cv2.imdecode(np.asarray(bytearray(raw)), cv2.IMREAD_COLOR)
So, you should need:
bucket = s3_resource.Bucket(bucket_name)
img = bucket.Object(key).get().get('Body').read()
nparray = cv2.imdecode(np.asarray(bytearray(img)), cv2.IMREAD_COLOR)
Hope This will be Best Solution For Mentioned Requirement, To read The Images from s3 bucket using URLs..!
import os
import logging
import boto3
from botocore.client import Config
from botocore.exceptions import ClientError
import numpy as np
import urllib
import cv2
s3_signature ={
'v4':'s3v4',
'v2':'s3'
}
def create_presigned_url(bucket_name, bucket_key, expiration=3600, signature_version=s3_signature['v4']):
s3_client = boto3.client('s3',
aws_access_key_id="AWS_ACCESS_KEY",
aws_secret_access_key="AWS_SECRET_ACCESS_KEY",
config=Config(signature_version=signature_version),
region_name='ap-south-1'
)
try:
response = s3_client.generate_presigned_url('get_object',
Params={'Bucket': bucket_name,
'Key': bucket_key},
ExpiresIn=expiration)
print(s3_client.list_buckets()['Owner'])
for key in s3_client.list_objects(Bucket=bucket_name,Prefix=bucket_key)['Contents']:
print(key['Key'])
except ClientError as e:
logging.error(e)
return None
# The response contains the presigned URL
return response
def url_to_image(URL):
resp = urllib.request.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
seven_days_as_seconds = 604800
generated_signed_url = create_presigned_url(you_bucket_name, bucket_key,
seven_days_as_seconds, s3_signature['v4'])
print(generated_signed_url)
image_complete = url_to_image(generated_signed_url)
#just debugging Purpose to show the read Image
cv2.imshow('Final_Image',image_complete)
cv2.waitKey(0)
cv2.destroyAllWindows()
Use For Loop to iterate to all Keys In The KeyList. Just Before calling the Function create_presigned_url.
Another alternative using download_fileobj and BytesIO:
from io import BytesIO
import cv2
import numpy as np
bucket = s3_resource.Bucket(bucket_name)
file_stream = BytesIO()
bucket.Object(key).download_fileobj(file_stream)
np_1d_array = np.frombuffer(file_stream.getbuffer(), dtype="uint8")
img = cv2.imdecode(np_1d_array, cv2.IMREAD_COLOR)
I am trying to display an image inside a Tkinter window through Web Scraping displaying a message from a certain point on the website that says in Portuguese "Capella Ganhou" or "Procyon Ganhou".
I tried to look in different forums for a solution but I couldn't find any that fixes the error in my situation. I also tested with print to make sure the string exists and is returning its value and also encapsulated it into a variable.
The source code and the error are below .
from tkinter import *
import urllib.request
from bs4 import BeautifulSoup
from IPython.display import Image, display
from PIL import Image, ImageTk
import io
def capella_tg():
resultado_tg = StringVar()
resultado_tg.set(soup.find_all("font")[5].string)
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
def procyon_tg():
resultado_tg = StringVar()
resultado_tg.set(soup.find_all("font")[4].string[3:])
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
def img_capella():
raw_data = urllib.request.urlopen("https://i.imgur.com/AHLqtt0.jpg").read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label1 = Label(root, image=image).pack()
def img_procyon():
raw_data = urllib.request.urlopen("https://i.imgur.com/TQyCnfD.jpg").read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label1 = Label(root, image=image).pack()
root = Tk()
with urllib.request.urlopen("http://www.cabaleasy.com") as url: page = url.read()
soup = BeautifulSoup(page, "html.parser")
#print(soup.find_all("font")[5].string)
try:
capella_tg()
except:
procyon_tg()
if capella_tg():
img_capella()
elif procyon_tg():
img_procyon()
root.mainloop()
-------ERROR---------
Traceback (most recent call last):
File "C:/Users/LucasDEV/PycharmProjects/LucasDEV/WEB_SCRAPPING/TESTES.py", line 49, in <module>
elif procyon_tg():
File "C:/Users/LucasDEV/PycharmProjects/LucasDEV/WEB_SCRAPPING/TESTES.py", line 17, in procyon_tg
resultado_tg.set(soup.find_all("font")[4].string[3:])
TypeError: 'NoneType' object is not subscriptable
#Dipen Shah That is why I used the try/except structure for. But it's not working and I'm getting the same error. I also tried this way:
def capella_tg():
resultado_tg = StringVar()
try:
resultado_tg.set(soup.find_all("font")[5].string)
label_resultado_tg = Label(root, textvariable=resultado_tg).pack()
except:
pass
i tested just using text and it works:
import urllib.request
from bs4 import BeautifulSoup
with urllib.request.urlopen("http://www.cabaleasy.com") as url: page = url.read()
soup = BeautifulSoup(page, "html.parser")
try:
print(soup.find_all("font")[5].string)
#At this moment, it will not be showing, cuz the status changes every hour
except:
print(soup.find_all("font")[4].string[3:])
i want to get images by url here on 6 and 7 lines, any help or ideas?
import urllib
import numpy as np
mkembed = ""
ourembed = ""
mkpic = cv2.imread("image.jpg")
ourpic = cv2.imread("image2.jpg")
difference = cv2.subtract(mkpic, ourpic)
b, g, r = cv2.split(difference)
if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
print("The images are completely Equal")```
Use the following code to get an image by url with cv2:
#import necessary packages
import numpy as np
import urllib.request as urllib
import cv2
#get image by url
resp = urllib.urlopen("https://homepages.cae.wisc.edu/~ece533/images/airplane.png")
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
#show image
cv2.imshow("Image", image)
cv2.waitKey()
I'm trying to use tkinter on python 3.2 to display an image from the Internet.
I'm getting TypeError: 'HTTPResponse' object is not callable.I know that this means I'm referencing a variable or function incorrectly.
I have read urllib "module object is not callable" but I'm still not sure how to fix this problem. Your help is appreciated.
import tkinter as tk
from urllib.request import urlopen
from PIL import ImageTk, Image
#http://docs.activestate.com/activepython/3.1/diveintopython3/html/porting-code- to-python-3-with-2to3.html
import io
img_file = urlopen('https://www.google.com/images/srpr/logo4w.png')
im = io.FileIO(img_file())<<<<<<<<<<<<<this line is throwing the error
resized_image = Image.open(im)
im.show()
root = tk.Tk()
img = ImageTk.PhotoImage(resized_image)
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
You can create a StringIO object instead:
from StringIO import StringIO
...
im = StringIO(img_file.read())
It behaves like a file, but it's not a file.