Un uomo libero, quando è sconfitto, non dà la colpa a nessuno.
Iosif Brodskij
Un uomo libero, quando è sconfitto, non dà la colpa a nessuno.
Iosif Brodskij
Here, we will discuss about image transformation: geometrical, color, point some image thresholding, image enhancement buy applying filters, editing GIF, drawing on an image, image conversion and modification in bulk and rolling image using PIL
.Pillow
is a fork of PIL- Python Imaging Library
that will support Python 3.x.
Installing pillow
library:
pip install PIL
The important class of the library: Image
Opening the image and getting details about it.
from PIL import Image
im = Image.open('simpson.png')
print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG
im.show()
#To open the image
As you can see from the comand:
print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG
the image has a RGBA color profile. We can convert it to jpeg only after converting it to RGB:
rgb_im = im.convert('RGB')
rgb_im.save('simpson_new.jpg')
Rotate an image:
from PIL import Image
import os
im = Image.open('simpson.png')
im = im.rotate(45) # rotate the object im 45 degrees
rgb_im = im.convert('RGB')
rgb_im.save('simpson_45.jpg')
im.close()
You can resize the image through the resize
command:
from PIL import Image
import os
im = Image.open('simpson.png')
rx = int(im.width/10)
ry = int(im.height/10)
im=im.resize((rx,ry)) #rx and ry are new pixel of image
rgb_im = im.convert('RGB')
rgb_im.save('simpson_resized.jpg')
im.close()
Add a text to immage:
from PIL import Image, ImageDraw, ImageFont
import os
im = Image.open('simpson.png')
d1 = ImageDraw.Draw(im)
myFont = ImageFont.truetype('Monofur/monofur bold Nerd Font Complete Mono Windows Compatible.ttf', 140)
d1.text((650,700), 'Hello World', font=myFont, fill=(255,255,0))
im.save('simpson_hello.png')
im.close()
Crop and paste the parts of the image:
from PIL import Image
import os
#path = # path of the image that you won't to open
#os.chdir(path)
im = Image.open('simpson.png')
print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG
box = (531,38,957,434) #Two points of a rectangle to be cropped
cropped_part = im.crop(box)
cropped_part = cropped_part.transpose(Image.ROTATE_180)
im.paste(cropped_part,box)
im.show()
#To open the image
Che a restare incinte siamo noi donne, che a partorire siamo noi donne, che a morire partorendo, o abortendo, siamo noi. E che la scelta tocca dunque a noi. A noi donne. E dobbiamo essere noi donne a prenderla, di volta in volta, di caso in caso, che a voi piaccia o meno.
Oriana Fallaci
…quanto le rimane del futuro.
– Philip Roth, da L’animale morente
Osserviamo che ogni file .jpg
, a un editor esadecimale, inizia con una sequenza FFD8
e termina con la sequenza FFD9
Il codice qui indicato “inietta” il messaggio “Hello World
” in coda al file image.jpg
senza però modificarne la qualità:
with open('image.jpg', 'ab') as f:
f.write(b"Hello World")
f.close()
Ecco come, all’editor esadecimale, appare adesso image.jpg
:
Dopo la sequenza FFD9
è stata inserita, come si è evidenziato nell’immagine, un flusso binario che rappresenta, appunto, la stringa Hello World
.
Se volessimo leggere il contenuto che abbiamo scritto in coda al file dopo la sequenza FFD9
:
with open('image.jpg', 'rb') as f:
content = f.read()
offset = content.index(bytes.fromhex('FFD9'))
f.seek(offset + 2)
print(f.read())
f.close()
Così ero solito paragonare cose grandi a cose piccole.
– Virgilio, Bucoliche, Ecloga prima, v 23
Lo scopo del codice è quello di realizzare un orologio analogico in Python, usando le librerie di PyQt6.
Iniziamo dal semplice schema realizzato con QT Designer, in cui c’è solo una QLabel (label_clock
) che occupa l’intero QWidget. Su tale label stamperemo, ogni secondo, l’orario. Salviamo lo schema (clock.ui
) e procediamo ad editare il codice di controllo.
La struttura iniziale del file è la seguente:
#!/usr/bin/python
from PyQt6.QtWidgets import QApplication, QWidget
from PyQt6 import uic
from PyQt6.QtCore import QTimer, QTime, Qt
import sys
class AppClock(QWidget):
def __init__(self):
super().__init__()
uic.loadUi('clock.ui', self)
self.setFixedSize(540, 164)
app = QApplication(sys.argv)
window = AppClock()
window.show()
app.exec()
Iniziamo a popolare il codice scrivendo il metodo della classe AppClock
che stamperà nella label_clock
l’orario corrente:
def displayTime(self):
currentTime = QTime.currentTime()
displayText = currentTime.toString('hh:mm:ss')
self.label_clock.setText(displayText) #
currentTime
;displayText
;displayText
nella label_clock
.Costruiamo, ora, l’oggetto timer
che si occuperà di richiamare la funzione currentTime
ogni secondo:
# timer is a instance of QTimer
timer = QTimer(self)
timer.timeout.connect(self.displayTime)
timer.start(1000) #1 second
Il progetto completo può essere scaricato da qui.
In this article we will see how we can create a calculator using PyQt6.
A calculator is something used for making mathematical calculations, in particular a small electronic device with a keyboard and a visual display. Below is the how the calculator will looks like
Here, you can download the code sources.
import matplotlib.pyplot as plt
import time
def timer(func):
def wrapper(*args, **kwargs):
before = time.time()
result = func(*args, **kwargs)
print('Function took:', time.time() - before, " seconds")
return result
return wrapper
@timer
def pattern_1(end_value):
start = 1
xs = []
ys = []
for val in range(start, end_value + 1):
if val > 1:
for n in range(2, val):
if (val % n) == 0:
break
else:
xs.append(val)
ys.append(val)
fig = plt.figure(figsize=(15, 15))
plt.polar(xs, ys, 'g.')
ax = plt.gca()
pattern_1(100)
plt.show()