How to set the pygame icon to an online image - python-3.x

So let's say I have a URL that stores an image, let's say it's, "https://www.image.site/img.png"
I want to set the pygame icon to that image without downloading anything on my computer.
I am already familiar with the code to set the icon to a file on your computer
img = pygame.image.load('image')
pygame.display.set_icon(img)
But how can I set it to an online image, would just setting the argument in set_icon to the URL work, or do I have to do something more complicated?

Another way:
Use the requests library to download the image bytes
Use BytesIO to create a file stream in memory
Create a PIL.Image from the byte file stream
Use pygame.image.fromstring to convert the PIL image to a pygame image
Here's the code:
import pygame
from io import BytesIO
import requests
from PIL import Image
# create image from URL
rsp = requests.get('https://www.pygame.org/docs/_static/pygame_tiny.png')
pilimage = Image.open(BytesIO(rsp.content)).convert("RGBA")
pgimg = pygame.image.fromstring(pilimage.tobytes(), pilimage.size, pilimage.mode)
# show image
pygame.init()
display = pygame.display.set_mode((250,150))
display.fill((255,255,255))
display.blit(pgimg,((250 - pgimg.get_rect().width)/2,(150 - pgimg.get_rect().height)/2))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); exit()
Output

I don't know why you'd do that, but I cooked something up for you.
It downloads the data of an image and then loads an image out of that data.
import requests
import io
import pygame
def surf_from_url(url):
data = io.BytesIO()
response = requests.get(url, stream=True)
if not response.ok:
print(response)
for block in response.iter_content(1024):
if not block:
break
data.write(block)
data.seek(0)
return pygame.image.load(data)
#demo
surf = surf_from_url("https://www.pygame.org/images/logo_lofi.png")
surf2 = surf_from_url("https://yt3.ggpht.com/a/AATXAJxybFq6Y8SFOuyvWqldJPcXbCps-gR_Qp2z4jKt=s100-c-k-c0xffffffff-no-rj-mo")
screen = pygame.display.set_mode([300,300])
pygame.display.set_icon(surf)
screen.fill((255,255,255))
screen.blit(surf, (0,0))
screen.blit(surf2, (20,100))
pygame.display.flip()

Related

Looping an OpenCV image inside a Tkinter label - using an esp32-cam

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()

Datamatrix with raspberry

I am trying to read datamatrix code by rasp using python.
I'm using pylibdmtx to read the code, but it only works on my notebook. When I put the same code on the raspberry it can't read the code. At the moment my raspberry is reading only qrcode and barcode.
I have two rasp one with raspbian and the other with ubuntu core, neither of which worked.
An example code below
import cv2
import time
from pylibdmtx.pylibdmtx import decode
data = None
video = cv2.VideoCapture(0)
video.set(cv2.CAP_PROP_FPS, 19)
while video.isOpened():
time.sleep(1/9)
ret, frame = video.read()
if ret is False:
break
decodeObjects = decode(frame,
timeout=1000,
max_count=1,
corrections=3)
for obj in decodeObjects:
if obj.data:
data = obj
if data:
break
video.release()
cv2.destroyAllWindows()
print(data)
pylibdmtx is just a wrapper for libdmtx. To make it work, you have to install the native library first.
The .whl file has already contained the .DLL file for Windows:
As for macOS and Linux, you can install the library via command-line tools.
Mac OS X:
brew install libdmtx
Linux:
sudo apt-get install libdmtx0a
I suppose there's no pre-built library for Raspberry Pi. So you can build it by yourself. Here is the source code:
https://github.com/dmtx/libdmtx
Take 3 steps to build and install the libdmtx library:
$ ./configure
$ make
$ sudo make install
After installing the libdmtx library, your Python code should work.
import cv2
import time
from pylibdmtx.pylibdmtx import decode
data = None
video = cv2.VideoCapture(0)
video.set(cv2.CAP_PROP_FPS, 19)
# Add
saveFilename = "./liveImage.jpg"
while video.isOpened():
time.sleep(1/9)
ret, frame = video.read()
if ret is False:
break
# Add - save Live Image
liveImage = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite(saveFilename, liveImage)
# Add - open File
loadImage = cv2.imread(saveFilename)
# Modify
decodeObjects = decode(loadImage,
timeout=1000,
max_count=1,
corrections=3)
for obj in decodeObjects:
if obj.data:
data = obj
if data:
break
video.release()
cv2.destroyAllWindows()
print(data)
import cv2
import time
from pylibdmtx.pylibdmtx import decode
data = None
video = cv2.VideoCapture(0)
video.set(cv2.CAP_PROP_FPS, 19)
# Add
saveFilename = "./liveImage.jpg"
while video.isOpened():
time.sleep(1/9)
ret, frame = video.read()
if ret is False:
break
# Add - save Live Image
liveImage = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite(saveFilename, liveImage)
# Add - open File
loadImage = cv2.imread(saveFilename)
# Modify
decodeObjects = decode(loadImage,
# Delete timeout=1000,
max_count=1,
corrections=3)
for obj in decodeObjects:
if obj.data:
data = obj
if data:
break
video.release()
cv2.destroyAllWindows()
print(data)

how to loop over all images and add border to all images in python?

I am working on image editing in python 3.7. I have a function which add border to all the images. But It returns only first image in folder and exists. This is my function:
from PIL import Image
import cv2
import numpy as np
import datetime
time = datetime.datetime.now()
def img_filter(img_in,border):
img = Image.open(border)
background = Image.open(img_in)
size = background.size
img = img.resize(size,Image.ANTIALIAS)
background = background.resize(size,Image.ANTIALIAS)
background.paste(img,(0,0),img)
saved = background.save(f"./img/1{time}.jpg")
print(saved)
img.close()
AND thats my code:
path = glob.glob("./img/*.jpg")
for img in path:
with open(img, 'rb') as file :
img = Image.open(file)
img_filter(img,'v.png')
please help me.
The time variable is global. So the value remains same for all the images. Either you can create time variable inside the img_filter method or you can create that variable inside the for loop and pass it as param to the method.
I personally would have preferred to create a curr_time variable inside the for loop.

How can I compare images on the web to see if they are the same in python3?

I am trying to write a script that compares images, and tells me whether or not the images are the same. Here is some minimal code:
import requests
url1 = 'https://scontent-lga3-1.cdninstagram.com/vp/b4577921aa35369af8980a3d563e4373/5DAE3C31/t51.2885-15/fr/e15/s1080x1080/66126877_342437073345261_1373504971257332049_n.jpg?_nc_ht=scontent-lga3-1.cdninstagram.com'
url2 = 'https://scontent-lga3-1.cdninstagram.com/vp/fab3372181d5ad596280d2c095a3496e/5DE99775/t51.2885-15/e35/67547020_369706770411768_8601267197685673619_n.jpg?_nc_ht=scontent-lga3-1.cdninstagram.com'
print(requests.Session().get(url1).content == requests.Session().get(url2).content)
However, if you manually navigate to each url you will see that the photos are the same. My question; Can I compare these images WITHOUT having to save them to a directory? I was thinking about perhaps reading these images both as binary, then doing the comparison, however I have no idea how to do that on the fly. Thanks for all of those who reply in advance.
If you want to see if two images are exactly the same, you can use BytesIO and PIL
import requests
from io import BytesIO
from PIL import Image
def get_image_data(img_url):
img = Image.open(requests.get(img_url, stream=True).raw).convert('RGB')
byteio = BytesIO()
img.save(byteio, format='PNG')
return byteio.getvalue()
url1 = 'https://scontent-lga3-1.cdninstagram.com/vp/b4577921aa35369af8980a3d563e4373/5DAE3C31/t51.2885-15/fr/e15/s1080x1080/66126877_342437073345261_1373504971257332049_n.jpg?_nc_ht=scontent-lga3-1.cdninstagram.com'
url2 = 'https://scontent-lga3-1.cdninstagram.com/vp/fab3372181d5ad596280d2c095a3496e/5DE99775/t51.2885-15/e35/67547020_369706770411768_8601267197685673619_n.jpg?_nc_ht=scontent-lga3-1.cdninstagram.com'
print(get_image_data(url1)==get_image_data(url2))
Though it seems these images have a slight difference between them, and this code returns false.
It would be better to take an approach which does not depend on the size of the image. Your two images could be a thumbnail and a full-sized image.
I would combine the approaches from:
#Tanner Clark Image comparison - fast algorithm
and the approach above:
import requests
from io import BytesIO
from PIL import Image, ImageFilter
import imagehash
def get_image(img_url):
img = Image.open(requests.get(img_url, stream=True).raw).convert('RGB')
byteio = BytesIO()
img.save(byteio, format='PNG')
return img
url1 = 'http://scontent-lga3-1.cdninstagram.com/vp/b4577921aa35369af8980a3d563e4373/5DAE3C31/t51.2885-15/fr/e15/s1080x1080/66126877_342437073345261_1373504971257332049_n.jpg?_nc_ht=scontent-lga3-1.cdninstagram.com'
url2 = 'http://scontent-lga3-1.cdninstagram.com/vp/fab3372181d5ad596280d2c095a3496e/5DE99775/t51.2885-15/e35/67547020_369706770411768_8601267197685673619_n.jpg?_nc_ht=scontent-lga3-1.cdninstagram.com'
def compare_images(url1, url2):
img1 = get_image(url1)
img2 = get_image(url2)
if img1.width<img2.width:
img2=img2.resize((img1.width,img1.height))
else:
img1=img1.resize((img2.width,img2.height))
img1=img1.filter(ImageFilter.BoxBlur(radius=3))
img2=img2.filter(ImageFilter.BoxBlur(radius=3))
phashvalue=imagehash.phash(img1)-imagehash.phash(img2)
ahashvalue=imagehash.average_hash(img1)-imagehash.average_hash(img2)
threshold = 1 # some experimentally valid value
totalaccuracy=phashvalue+ahashvalue
print(totalaccuracy)
return totalaccuracy <= threshold
print(compare_images(url1, url2))

Using QtWebKit for screenshot - result: white images

I would like to save web page as a PNG image using QtWebKit (pyQt).
I found following code on the internet, but as an output I get white image:
import sys
import signal
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebPage
def onLoadFinished(result):
if not result:
print "Request failed"
sys.exit(1)
# Set the size of the (virtual) browser window
webpage.setViewportSize(QSize(640,480))
# Paint this frame into an image
image = QImage(QSize(640,480), QImage.Format_ARGB32)
paint = QPainter(image)
print webpage.mainFrame().toHtml()
webpage.mainFrame().render(paint)
paint.end()
image.save("output.png")
sys.exit(0)
app = QApplication(sys.argv)
signal.signal(signal.SIGINT, signal.SIG_DFL)
webpage = QWebPage()
webpage.connect(webpage, SIGNAL("loadFinished(bool)"), onLoadFinished)
webpage.mainFrame().load(QUrl("http://maps.googleapis.com/maps/api/streetview?size=640x480&location=50.073723,14.43037&pitch=-0.760&sensor=false&heading=-169.73968469794528"))
sys.exit(app.exec_())
It saves correctly other pages that I've tested, but can't handle Google Street View.
print webpage.mainFrame().toHtml()
shows that proper web page is loaded, but somehow it doesn't render it... Do you know why?
I use: PyQt4-4.10.2-gpl-Py2.7-Qt4.8.4-x64

Resources