def resize(self, width, height, name='', type='width'): output = os.path.join(self.cdir, self.name + '-' + str(width) + 'x' + str(height) + '-' + name + self.ext) with open(self.src, 'r+b') as f: with Image.open(f) as image: if type == 'contain': try: result = resizeimage.resize_cover(image, [width, height]) except: tmp = resizeimage.resize_contain(image, [width, height]) result = resizeimage.resize_cover(tmp, [width, height]) elif type == 'height': result = resizeimage.resize_height(image, height, validate=False) elif type == 'crop': tmp = resizeimage.resize_contain(image, [width + 150, height + 150]) result = resizeimage.resize_crop(tmp, [width, height]) elif type == 'tcrop': tmp = resizeimage.resize_contain(image, [width, height]) result = resizeimage.resize_crop(tmp, [width, height]) elif type == 'thumbnail': result = resizeimage.resize_thumbnail(image, [width, height]) else: result = resizeimage.resize_width(image, width, validate=False) result.save(output, optimize=True) return [output, '[{}x{}] {}'.format(width, height, name), self.name + '-' + str(width) + 'x' + str(height) + '-' + name + self.ext, name]
def convertimage(imagefile, newfile): with Image.open(imagefile) as im: ratio = 0.15 width = int(im.width * ratio) height = int(im.height * ratio) if DEBUG: logging.info('%s resized to %d x %d' % (imagefile, width, height)) im = resizeimage.resize_thumbnail(im, [width, height]) im.save(newfile, im.format)
def resize_jpg(): for file in glob.glob("*.jpg"): fd_img = open(file, 'r+b') img = Image.open(fd_img) img = resizeimage.resize_thumbnail(img, [128, 128]) name = file.split(".") # Save them in the directory with the prefix resize img.save('resize-' + name[0] +'.jpeg', img.format) fd_img.close()
def test_resize_thumbnail(self): """ Test that the image resized with resize_thumbnail has the expected size """ with self._open_test_image() as img: img = resizeimage.resize_thumbnail(img, [200, 200]) filename = self._tmp_filename('resize-thumbnail.jpeg') img.save(filename, img.format) with Image.open(filename) as image: self.assertEqual(image.size, (200, 133))
def resize_image(self, img_path, width = 220, height = 220): resize_thumb_jpg_path = self.dir_name + '/thumb.jpg' try: fd_img = open(img_path, 'r+b') img = Image.open(fd_img) img = resizeimage.resize_thumbnail(img, [height, width]) img.save(resize_thumb_jpg_path, img.format) fd_img.close() os.remove(img_path) except imageexceptions.ImageSizeError: # shutil.copyfile(img_path, resize_thumb_jpg_path) os.renames(img_path, resize_thumb_jpg_path)
def MakeThumbnails(source): # Thumbnail image size tnSize = [200, 200] for head in os.listdir(os.path.join(source, "img")): for d in os.listdir(os.path.join(source, "img", head)): print "Processing {} for thumbnail generation".format(d) for f in os.listdir(os.path.join(source, "img", head, d)): if isValidImage(f): tnFileName = "tn_" + f try: with open(os.path.join(source, "img", head, d, f), 'r+b') as p: with Image.open(p) as im: try: tn = ri.resize_thumbnail(im, tnSize) except: print "ERROR: resize failed" try: tn.save(os.path.join(source, "img", head, d, tnFileName), "JPEG") except: print "ERROR: save failed" except IOError: print "cannot create thumbnail for: " + f
from PIL import Image from resizeimage import resizeimage import matplotlib.pyplot as plt image_path = 'deconvnet/images/tesla_fat_3ch.png' img_pil_read = Image.open(image_path) # original image img_pil_resized = img_pil_read.resize((224, 224), Image.ANTIALIAS) img_crop_resized = resizeimage.resize_crop(img_pil_read, [224, 224]) img_cover_resized = resizeimage.resize_cover(img_pil_read, [224, 224]) img_contain_resized = resizeimage.resize_contain(img_pil_read, [224, 224]) img_thumbnail_resized = resizeimage.resize_thumbnail(img_pil_read, [224, 224]) # image show fig = plt.figure() ax1 = fig.add_subplot(231) plt.imshow(img_pil_read) plt.title('origin') ax2 = fig.add_subplot(232) plt.imshow(img_pil_resized) plt.title('PIL resize') ax3 = fig.add_subplot(233) plt.imshow(img_crop_resized) plt.title('crop') ax4 = fig.add_subplot(234) plt.imshow(img_cover_resized) plt.title('cover') ax5 = fig.add_subplot(235) plt.imshow(img_contain_resized) plt.title('contain')
def afficher_film_local(self, film): """ Affiche les données d'un film en base :param film: le film à afficher """ # affiche if film['affiche'] is not None: image = ImageTk.PhotoImage( resizeimage.resize_thumbnail( Image.open(io.BytesIO(film['affiche'])), [400, 200])) else: image = ImageTk.PhotoImage( resizeimage.resize_thumbnail(Image.open("afficheDefaut.jpg"), [400, 200])) self.label_affiche = ttk.Label(self, image=image) self.label_affiche.img = image # titre self.label_titre = ttk.Label(self, text=film['titre'], font='bold 16') # annee if film['annee'] is not None: self.label_annee = ttk.Label(self, text=str(film['annee'])) # duree if film['duree'] is not None: self.label_duree = ttk.Label( self, text=('Durée : ' + str(film['duree']) + ' minutes')) # saison if film['saison'] is not None and film['saison'] > 0: self.label_saison = ttk.Label(self, text=('Saisons : ' + str(film['saison']))) # note générale if film['note_gen'] is not None: self.label_note = ttk.Label(self, text=str(film['note_gen']) + '/10') # le type de film self.label_type = ttk.Label(self, text=get_type(film['type'])) # est à acheter ou non self.label_a_acheter = ttk.Label( self, text=('A acheter : ' + ('Oui' if film['a_acheter'] is True else 'Non'))) # est à voir self.label_a_voir = ttk.Label( self, text=('A voir : ' + ('Oui' if film['a_voir'] is True else 'Non'))) # collection if film['collection'] is not None: self.label_collection = ttk.Label( self, text=('De la collection : ' + film['collection']['titre'])) # boutons self.frame_boutons = ttk.Frame(self) self.button_supprimer = ttk.Button( self.frame_boutons, text="Supprimer", command=lambda: self.supprimer_film(film['id'])) self.button_supprimer.pack(side=tk.LEFT) self.button_vu = ttk.Button( self.frame_boutons, text="Vu !" if film['a_voir'] is True else 'A voir !', command=lambda: self.film_vu(film['id'])) self.button_vu.pack(side=tk.LEFT) if film['a_acheter'] is True: self.button_achete = ttk.Button( self.frame_boutons, text="Acheté !", command=lambda: self.film_achete(film['id'])) self.button_achete.pack(side=tk.LEFT) # histoire self.label_synopsis = ttk.Label(self, text=film['synopsis'], wraplength=500) # genres self.frame_genres = ttk.Frame(self) titre_lab_genre = ttk.Label(self.frame_genres, text='Genres : ', font='bold') titre_lab_genre.pack(side=tk.LEFT) if len(film['genres']) > 0: for genre in film['genres']: lab_genre = ttk.Label(self.frame_genres, text=genre['titre']) lab_genre.pack(side=tk.LEFT) # producteurs if len(film['producteurs']) > 0: r = 0 c = 1 self.frame_producteurs = ttk.Frame(self) titre_lab_producteurs = ttk.Label(self.frame_producteurs, text='Producteurs : ', font='bold') titre_lab_producteurs.grid(row=0, column=0) for producteur in film['producteurs']: lab_producteur = ttk.Label(self.frame_producteurs, text=producteur['nom']) lab_producteur.grid(row=r, column=c) c += 1 if c is 4: c = 0 r += 1 # realisateurs if len(film['realisateurs']) > 0: r = 0 c = 1 self.frame_realisateurs = ttk.Frame(self) titre_lab_realisateurs = ttk.Label(self.frame_realisateurs, text='Réalisateurs : ', font='bold') titre_lab_realisateurs.grid(row=0, column=0) for realisateur in film['realisateurs']: lab_realisateur = ttk.Label(self.frame_realisateurs, text=realisateur['nom']) lab_realisateur.grid(row=r, column=c) c += 1 if c is 4: c = 0 r += 1 # casting if len(film['acteurs']) > 0: r = 0 c = 1 self.frame_acteurs = ttk.Frame(self) titre_lab_acteurs = ttk.Label(self.frame_acteurs, text='Acteurs : ', font='bold') titre_lab_acteurs.grid(row=0, column=0) for acteur in film['acteurs']: lab_acteur = ttk.Label(self.frame_acteurs, text=(acteur['nom'] + '(' + acteur['role'] + ')')) lab_acteur.grid(row=r, column=c) c += 1 if c is 4: c = 0 r += 1 # affichage des éléments self.label_affiche.grid(row=0, column=0, rowspan=12) self.label_titre.grid(row=0, column=1) if film['annee'] is not None: self.label_annee.grid(row=1, column=1) if film['duree'] is not None: self.label_duree.grid(row=2, column=1) if film['saison'] is not None and film['saison'] > 0: self.label_saison.grid(row=3, column=1) if film['note_gen'] is not None: self.label_note.grid(row=4, column=1) self.label_type.grid(row=5, column=1) self.label_a_acheter.grid(row=6, column=1) self.label_a_voir.grid(row=7, column=1) if film['collection'] is not None: self.label_collection.grid(row=8, column=1) if len(film['genres']) > 0: self.frame_genres.grid(row=9, column=1) if len(film['producteurs']) > 0: self.frame_producteurs.grid(row=10, column=1) if len(film['realisateurs']) > 0: self.frame_realisateurs.grid(row=11, column=1) self.frame_boutons.grid(row=12, column=0) if len(film['acteurs']) > 0: self.frame_acteurs.grid(row=13, column=0, columnspan=2) self.label_synopsis.grid(row=14, column=0, columnspan=2)
from PIL import Image from resizeimage import resizeimage import os dir = 'inputs/' dir_output = 'inputs_cropped/' files = [f for f in os.listdir(dir)] # check extension if necessary WIDTH = 28 HEIGHT = 28 for f in files: print(f) fd_img = open(dir + f, 'r+b') img = Image.open(fd_img) img = resizeimage.resize_thumbnail(img, [WIDTH, HEIGHT]) # this keeps the ratio img = img.rotate(270, expand=True) # img = resizeimage.resize_crop(img, [32, 32]) # this crops the image creating a box with the given dimensions # img = resizeimage.resize_contain(img, [32, 32]) # resize the image so that it can fit in the specified area, keeping the ratio and without crop img.save(dir_output + f, img.format) fd_img.close()
def thumb(img, width, height): return resizeimage.resize_thumbnail(img, [int(width), int(height)], Image.LANCZOS)
def resize_file(in_file, out_file, size): image = resizeimage.resize_thumbnail(PIL.Image.open(in_file), size) image.save(out_file) image.close()
x = "X" op = "+" result = "%d %s %s %d = %s" % (s1, x, op, s2, s_temp) s_temp = "%.2f" % (s_temp) print(result) print(s0) pic_original = 'D:\\pic\\pic\\' pic_ready = 'D:\\pic\\ready\\' pic_set = [] for filename in os.listdir(pic_original): if filename.endswith('.jpg'): with open("%s%s" % (pic_original, filename), 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_thumbnail(image, [500, 300]) newpath = "%s%s" % (pic_ready, filename) cover.save(newpath, image.format) pic_set.append(newpath) doc = DocxTemplate("template.docx") context = { 'myimage': InlineImage(doc, pic_set[0], width=Mm(100), height=Mm(50)), 'myimage1': InlineImage(doc, pic_set[1], width=Mm(100), height=Mm(50)), 'myimage2': InlineImage(doc, pic_set[2], width=Mm(100), height=Mm(50)), 'myimage3': InlineImage(doc, pic_set[3], width=Mm(200), height=Mm(150)), 'myimage4': InlineImage(doc, pic_set[4], width=Mm(200), height=Mm(150)), 'myimage5': InlineImage(doc, pic_set[5], width=Mm(200), height=Mm(150)), 'myimage6': InlineImage(doc, pic_set[6], width=Mm(200), height=Mm(150)), 'myimage7': InlineImage(doc, pic_set[7], width=Mm(200), height=Mm(150)), 'myimage8': InlineImage(doc, pic_set[8], width=Mm(200), height=Mm(150)),
h5 = "ETES VOUS UN HOMME OU UNE FEMME ?" h6 = "QUELLE EST VOTRE PSEUDO ?" h7 = "VOUS ETES UN HOMME !" h8 = "VOUS ETES UNE FEMME !" h9 = "EXCELLENT ! VOUS VOILA AUX PORTES DE LA GLOIRE !\n" + " MAIS QUELLE EST VOTRE PSEUDO?" h10 = h + "EXCELLENT ! VOUS VOILA AUX PORTES DE LA GLOIRE !\n" + "JE VOUS LAISSE MAINTENANT AVEC LE COMMANDANT COUSTEAU.\n" + h h11 = h + "BONJOUR MON EMPEREUR, DES ESCALVES CE SONT REGROUPES SUR \n" + "LA PLACE D'ITALIE, QUE DOIS JE FAIRE ?\n" + "CHOIX 1: 'TUEZ LES TOUS !'\n" + "CHOIX 2: 'LAISSEZ LES POUR UNE FOIS..'\n" + h h12 = h + " TUEZ LES TOUS !\n" + h h13 = h + " LAISSEZ LES POUR CETTE FOIS...\n" + h h14 = h + "SEIGNEUR, SEIGNEUR ! MA FERME EST ATTAQUE !\n" + "DES BARBARES VEULENT ENVAHIR L'EMPIRE QUE DEVONS \n" + " NOUS FAIRE ?\n" + "CHOIX 1: 'ON RIPOSTE !'\n" + "CHOIX 2: 'NE FAITES RIEN, ILS VONT SE CALMER...'\n" + h h15 = "ON RIPOSTE !" h16 = " NE FAITES RIEN,ILS VONT SE CALMER" TAILLE = [466 * factorW, 646 * factorH] phot = Image.open('image_principall.png', 'r') phot = resizeimage.resize_thumbnail(phot, TAILLE) phot.save('image_principal2.png', phot.format) photo = PhotoImage(file="image_principal2.png") TAILLE = [150 * factorW, 237 * factorH] phot = Image.open("mouse.png", 'r') phot = resizeimage.resize_thumbnail(phot, TAILLE) phot.save('mouse2.png', phot.format) photoSouris = PhotoImage(file="mouse2.png") TAILLE = [619 * factorW, 491 * factorH] choix = 0 fenHistoire = Canvas(fenetre, width=1615 * factorW,
def fraction(self, pos, frac="(1+2)/(3*2)", commander='', allow_scalling=True, n_margin=0, d_margin=0): """ >> tutorial: << pos : position for writing . frac : pure fraction fourmela. ex:"5+5/3*4". n_margin, d_margin: numerator & denominator margins from the division sign. ##### fix it make it auto detected. return_only_width : True to return only width of fraction. nw, nd, dsign : numerator & denominator & division sign widths. length : division sign length. """ nd = frac.split("/") for i,j in enumerate(nd): leven = lambda x: True if x.count("(")-x.count(")") == 1 else False reven = lambda x: True if x.count(")")-x.count("(") == 1 else False l, r = "/".join(nd[:i+1]), "/".join(nd[i+1:]) if leven(l) and reven(r):n, d= l[2:], r[:-1] nc, dc = n, d ########################### if self.dominsaver: n_margin = n_margin d_margin = d_margin elif not self.dominsaver: #especial case (n_margin & d_margin). d_margin = 10 n_margin = 0 self.dominsaver = True ########################### #print(n) n = self.robot((0,0), n, commander="fraction") d = self.robot((0,0), d, commander="fraction") if nc[:2]=="f(" and allow_scalling: nw, nh = n.size[0], n.size[1] n = resizeimage.resize_thumbnail(n, [nw-20, nh-20]) if dc[:2]=="f(" and allow_scalling: dw, dh = d.size[0], d.size[1] d = resizeimage.resize_thumbnail(d, [dw-20, dh-20]) def figure(n, d, length): figure.nw = n.size figure.dw = d.size figure.dsign = self.draw.textsize(text='_'*length, font=self.fnt) return length if figure.dsign[0] > max([figure.nw[0], figure.dw[0]]) else figure(n, d, length+1) length = figure(n, d, 1) self.d_sign_width = figure.dsign[0] size = (self.draw.textsize(text='_'*length, font=self.fnt)[0], figure.nw[1]+figure.dw[1]+n_margin+d_margin) nf, df = ((figure.dsign[0]-figure.nw[0])//2, 0), ((figure.dsign[0]-figure.dw[0])//2,figure.nw[1]+n_margin+d_margin) #if commander=="fraction0":df = ((figure.dsign-figure.dw[0])//2,figure.nw[1]+n_margin+d_margin) if nc[:2]=="f(":nf = ((figure.dsign[0]-figure.nw[0])//2, 0) ds_offset = self.fnt.getoffset( "_"*length) #(devision sign) this is pain in the ass, screw it. frac = self.cage(size, ["p", n, nf, n], ["p", d, df, d], ["t", (0, figure.nw[1]+n_margin-ds_offset[1]), "_"*length, "black", self.fnt], show=False) if commander != "": self.uniqued["f("+nc+"/"+dc+")"] = figure.dw[1]+d_margin self.uniquen["f("+nc+"/"+dc+")"] = figure.nw[1]+n_margin return frac pos = (pos[0]-figure.dsign[0], pos[1]-figure.nw[1]-n_margin-figure.dsign[1]+ds_offset[1]) self.img.paste(frac,pos, frac )
def resize_file(in_path, out_path, size): with open(in_path, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_thumbnail(image, size) cover.save(out_path, image.format)
def th(src_path, dst_folder="thumbs"): dst_path = Path(dst_folder) / src_path with open(src_path, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_thumbnail(image, [150, 150]) cover.save(dst_path, image.format)
extensions = (".jpg",".jpeg",".JPG",".JPEG") for ext in extensions: print(ext) #Recursively search for JPG files and get the path to them for f in glob.glob('./**/**/*'+ext): name = os.path.basename(f) #Get the file name print(os.path.basename(f)) split = f.split('/') #Split the complete path in parts split2 = split[2].split('-') imgexif = open(f, 'rb') tags = exifread.process_file(imgexif) rotation = str(tags['Image Orientation']) img = Image.open(f,) #Open source image print('Opening '+f) img = resizeimage.resize_thumbnail(img, [1024, 1024]) #Resize the image with a maximum Width or Heigh of 1024 print(rotation) if not re.search(r'\Horizontal\b',rotation): print('1') img=img.rotate(-90, expand=True) if os.path.isfile('/home/michael/ownCloud/Photos/'+split[1]+'/1024_'+name): print('Image already exists') img.close() else: print ('Saving new file in /home/michael/ownCloud/Photos/'+split2[0]+'_'+split2[1]+'/1024_'+name) path = '/home/michael/ownCloud/Photos/'+split2[0]+'_'+split2[1]+'/' if not os.path.exists(path): os.makedirs(path) img.save('/home/michael/ownCloud/Photos/'+split2[0]+'_'+split2[1]+'/1024_'+name, img.format) #Save image to owncloud directory img.close() #Close source image input("Press Enter to continue...")
for ext in extensions: print(ext) #Recursively search for JPG files and get the path to them for f in glob.glob('./**/**/*' + ext): name = os.path.basename(f) #Get the file name print(os.path.basename(f)) split = f.split('/') #Split the complete path in parts split2 = split[2].split('-') imgexif = open(f, 'rb') tags = exifread.process_file(imgexif) rotation = str(tags['Image Orientation']) img = Image.open(f, ) #Open source image print('Opening ' + f) img = resizeimage.resize_thumbnail( img, [1024, 1024 ]) #Resize the image with a maximum Width or Heigh of 1024 print(rotation) if not re.search(r'\Horizontal\b', rotation): print('1') img = img.rotate(-90, expand=True) if os.path.isfile('/home/michael/ownCloud/Photos/' + split[1] + '/1024_' + name): print('Image already exists') img.close() else: print('Saving new file in /home/michael/ownCloud/Photos/' + split2[0] + '_' + split2[1] + '/1024_' + name) path = '/home/michael/ownCloud/Photos/' + split2[0] + '_' + split2[ 1] + '/' if not os.path.exists(path):
def resize_file(in_file, out_file, size): with open(in_file) as fd: image = resizeimage.resize_thumbnail(Image.open(fd), size) image.save(out_file) image.close()
def afficher_film_internet(self, film, casting, affiche): """ Méthode pour afficher un film provenant d'internet :param film: le film à afficher :param casting: son casting et équipe technique :param affiche: l'affiche du film """ # affichage de l'affiche if affiche is not None: image = ImageTk.PhotoImage( resizeimage.resize_thumbnail(affiche, [400, 200])) else: image = ImageTk.PhotoImage( resizeimage.resize_thumbnail(Image.open("afficheDefaut.jpg"), [400, 200])) self.label_affiche = ttk.Label(self, image=image) self.label_affiche.img = image # titre self.label_titre = ttk.Label( self, text=film['title'] if 'title' in film else film['name'], font='bold 16') # année if ('release_date' in film and film['release_date'] is not None) or \ ('first_air_date' in film and film['first_air_date'] is not None) : self.label_annee = ttk.Label( self, text='Année : ' + str(film['release_date'][:4] if 'release_date' in film else film['first_air_date'][:4])) # durée if ('runtime' in film and film['runtime'] is not None) or \ ('episode_run_time' in film and film['episode_run_time'] is not None): self.label_duree = ttk.Label( self, text='Durée : ' + str(film['runtime'] if 'runtime' in film else film['episode_run_time'][:4])) # nombre de saisons if 'number_of_seasons' in film and film[ 'number_of_seasons'] is not None and film[ 'number_of_seasons'] > 0: self.label_saison = ttk.Label( self, text=('Saisons : ' + str(film['number_of_seasons']))) # note if 'vote_average' in film and film['vote_average'] is not None: self.label_note = ttk.Label(self, text=str(film['vote_average']) + '/10') # collection if 'belongs_to_collection' in film and film[ 'belongs_to_collection'] is not None: self.label_collection = ttk.Label( self, text='Collection : ' + str(film['belongs_to_collection']['name'])) # genres self.frame_genres = ttk.Frame(self) titre_lab_genre = ttk.Label(self.frame_genres, text='Genres : ', font='bold') titre_lab_genre.pack(side=tk.LEFT) if len(film['genres']) > 0: for genre in film['genres']: lab_genre = ttk.Label(self.frame_genres, text=genre['name']) lab_genre.pack(side=tk.LEFT) # producteurs liste_producteurs = [ item for item in casting['crew'] if 'producer' in str(item['job']).lower() ] if len(liste_producteurs) > 0: r = 0 c = 1 self.frame_producteurs = ttk.Frame(self) titre_lab_producteurs = ttk.Label(self.frame_producteurs, text='Producteurs : ', font='bold') titre_lab_producteurs.grid(row=0, column=0) for producteur in liste_producteurs: lab_producteur = ttk.Label(self.frame_producteurs, text=producteur['name']) lab_producteur.grid(row=r, column=c) c += 1 if c is 4: c = 0 r += 1 # réalisateurs liste_realisateurs = [ item for item in casting['crew'] if 'director' in str(item['job']).lower() ] if len(liste_realisateurs) > 0: r = 0 c = 1 self.frame_realisateurs = ttk.Frame(self) titre_lab_realisateurs = ttk.Label(self.frame_realisateurs, text='Réalisateurs : ', font='bold') titre_lab_realisateurs.grid(row=0, column=0) for realisateur in liste_realisateurs: lab_realisateur = ttk.Label(self.frame_realisateurs, text=realisateur['name']) lab_realisateur.grid(row=r, column=c) c += 1 if c is 4: c = 0 r += 1 # casting principal if len(casting['cast']) > 0: r = 0 c = 1 self.frame_acteurs = ttk.Frame(self) titre_lab_acteurs = ttk.Label(self.frame_acteurs, text='Acteurs : ', font='bold') titre_lab_acteurs.grid(row=0, column=0) for acteur in casting['cast'][:10]: lab_acteur = ttk.Label(self.frame_acteurs, text=(acteur['name'] + '(' + acteur['character'] + ')')) lab_acteur.grid(row=r, column=c) c += 1 if c is 4: c = 0 r += 1 # bouton d'ajout en base self.button_ajout = ttk.Button( self, text="Ajouter à la bibliothèque", command=lambda: self.ajouter_film( film['id'], film['title'] if 'title' in film else film['name'], affiche)) # histoire self.label_synopsis = ttk.Label(self, text=film['overview'], wraplength=500) # affichage des élements self.label_affiche.grid(row=0, column=0, rowspan=9) self.label_titre.grid(row=0, column=1) if ('release_date' in film and film['release_date'] is not None) or \ ('first_air_date' in film and film['first_air_date'] is not None): self.label_annee.grid(row=1, column=1) if ('runtime' in film and film['runtime'] is not None) or \ ('episode_run_time' in film and film['episode_run_time'] is not None): self.label_duree.grid(row=2, column=1) if 'number_of_seasons' in film and film[ 'number_of_seasons'] is not None and film[ 'number_of_seasons'] > 0: self.label_saison.grid(row=3, column=1) if 'vote_average' in film and film['vote_average'] is not None: self.label_note.grid(row=4, column=1) if 'belongs_to_collection' in film and film[ 'belongs_to_collection'] is not None: self.label_collection.grid(row=5, column=1) if len(film['genres']) > 0: self.frame_genres.grid(row=6, column=1) if len(liste_producteurs) > 0: self.frame_producteurs.grid(row=7, column=1) if len(liste_realisateurs) > 0: self.frame_realisateurs.grid(row=8, column=1) if not verifier_film_en_base(film['id'], self.type): self.button_ajout.grid(row=9, column=0) if len(casting['cast']) > 0: self.frame_acteurs.grid(row=10, column=0, columnspan=2) self.label_synopsis.grid(row=11, column=0, columnspan=2)
cv.imshow('draw', bg) k = cv.waitKey(1) if (k == 27 & 0xFF) or ((len(point) // 2) == len(mark_index)): point = np.array(point).reshape((-1, 2)) paths.append(path) count += 1 print("done - " + str(count)) cv.destroyAllWindows() # Put the marks on selected points box = [] for i, m in enumerate(mark_index): fg_pi = pi_marks[m][random.choice([0, 1, 2, 3])].copy() re_size = random.choice([1, 2, 3, 4]) fg_pi = resizeimage.resize_thumbnail( fg_pi, [fg_pi.size[0] // re_size, fg_pi.size[1] // re_size]) cox, coy = int(point[i][0]), int(point[i][1]) box.append([cox, coy, int(fg_pi.size[1]), int(fg_pi.size[0])]) # x, y, h, w bg_pi.paste(fg_pi, (cox, coy), fg_pi) bbox.append(box) bg_pi.show() bg_pi.save( path.replace("/random_images/", "/random_images/mark_added/")) point = [] break
def image_to_display(path, start=None, length=None): """ Display an image """ rows, columns = os.popen('stty size', 'r').read().split() if not start: start = c['IMAGE_SHIFT'] if not length: length = int(columns) - 2 * start i = Image.open(path) i = i.convert('RGBA') w, h = i.size i.load() width = min(w, length) height = int(float(h) * (float(width) / float(w))) if c['IMAGE_RESIZE_TO_FIT'] is True: # If it image won't fit in the terminal without scrolling shrink it # Subtract 3 from rows so the tweet message fits in too. h = 2 * (int(rows) - 3) if height >= h: width = int(float(width) * (float(h) / float(height))) height = h if (height <= 0) or (width <= 0): raise ValueError("image has negative dimensions") height = min(height, c['IMAGE_MAX_HEIGHT']) # Sixel if c['IMAGE_ON_TERM'] == 'sixel': import fcntl, struct, termios from io import BytesIO from libsixel import sixel_dither_new, sixel_dither_initialize, sixel_encode, sixel_output_new, SIXEL_PIXELFORMAT_RGBA8888 from resizeimage import resizeimage # FIXME: rows and columns are gotten a second time. Maybe use this at # the begining of function instead of the call to stty size farg = struct.pack("HHHH", 0, 0, 0, 0) fd_stdout = sys.stdout.fileno() fretint = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, farg) rows, columns, xpixels, ypixels = struct.unpack("HHHH", fretint) max_width_pixels = width * (xpixels // columns) max_height_pixels = height * (ypixels // rows) # FIXME: This way is preferable to avoid an addition dependency, but it doesn't work correctly # i = i.resize((max_width_pixels, max_height_pixels), Image.ANTIALIAS) i = resizeimage.resize_thumbnail(i, [max_width_pixels, max_height_pixels]) sixel = BytesIO() dither = sixel_dither_new(256) sixel_dither_initialize(dither, i.tobytes(), i.width, i.height, SIXEL_PIXELFORMAT_RGBA8888) sixel_encode(i.tobytes(), i.width, i.height, 1, dither, sixel_output_new(lambda imgdata, sixel: sixel.write(imgdata), sixel)) sys.stdout.write('%s%s' % (' ' * start, sixel.getvalue().decode('ascii'))) # SGR else: i = i.resize((width, height), Image.ANTIALIAS) for real_y in xrange(height // 2): sys.stdout.write(' ' * start) for x in xrange(width): y = real_y * 2 p0 = i.getpixel((x, y)) p1 = i.getpixel((x, y + 1)) block_print(p1, p0) sys.stdout.write('\n')
jpegfile = BytesIO() image = Image.open(imagefile) image.save(jpegfile, "JPEG", quality=60) jpegfile.seek(0) print('Saving Image: ' + jpeg_img_name) writeImage(service, args, jpeg_img_name + '.jpeg', jpegfile) print('Saving Thumbnail: ' + jpeg_img_name) cover = resizeimage.resize_thumbnail(image, [100, 200]) thumbnailfile = BytesIO() cover.save(thumbnailfile, 'PNG') thumbnailfile.seek(0) writeImage(service, args, jpeg_img_name + '_thumbnail.png', thumbnailfile) print('Image Saved: ' + jpeg_img_name) ocrData = ocrImage( service, args, args.storageUrl + args.container + "/" + args.folder + "/" + args.volume + "/" + jpeg_img_name + '.jpeg', jpeg_img_name)
import scipy.misc @adapt_rgb(hsv_value) def equal_hsv(image): return exposure.equalize_hist(image) file_dir = r'C:\PhD\Comet_data\Comet_Hale_Bopp\all_images' im_out_dir = os.path.join(file_dir,'equalised') if not os.path.exists(im_out_dir): os.makedirs(im_out_dir) imgs = os.listdir(file_dir) imgs = [x for x in imgs if "." in x] for i in range(len(imgs)): imagepath = os.path.join(file_dir,imgs[i]) with open(imagepath, 'r+b') as img: with Image.open(img) as image: re_img = resizeimage.resize_thumbnail(image, [100, 100]) pix = np.array(re_img) img_eq = equal_hsv(pix) im_out_base = 'HaleBopp' + str(i) + '.png' im_out = os.path.join(im_out_dir,im_out_base) scipy.misc.imsave(im_out,img_eq)
# -*- coding: utf-8 -*- """ Created on Sun Jan 19 21:59:40 2020 @author: Harish """ from PIL import Image from resizeimage import resizeimage fd_img = open(r'C:\Users\Harish\Desktop\Plant project repo\plant-project\code\test6.jpg', 'r') img = Image.open(fd_img) img = resizeimage.resize_thumbnail(img, [200, 200]) img.save('test-image-thumbnail.jpeg', img.format) fd_img.close()
def image_optimizer(image_data, output_size=None, resize_method=None): """Optimize an image that has not been saved to a file.""" if OPTIMIZED_IMAGE_METHOD == 'pillow': image = Image.open(image_data) bytes_io = BytesIO() file_name = image_data.name extension = get_file_extension(file_name) # If output_size is set, resize the image with the selected # resize_method. 'thumbnail' is used by default if output_size is not None: if resize_method is None: pass elif resize_method is 'thumbnail': image = resizeimage.resize_thumbnail(image, output_size, resample=Image.LANCZOS) elif resize_method is 'cover': image = resizeimage.resize_cover(image, output_size, validate=False) else: raise Exception( 'optimized_image_resize_method misconfigured, it\'s value must be \'thumbnail\', \'cover\' or None' ) output_image = Image.new('RGBA', output_size, BACKGROUND_TRANSPARENT) output_image_center = (int((output_size[0] - image.size[0]) / 2), int((output_size[1] - image.size[1]) / 2)) output_image.paste(image, output_image_center) # If output_size is None the output_image would be the same as source else: output_image = image # If the file extension is JPEG, convert the output_image to RGB if extension == 'JPEG': output_image = output_image.convert("RGB") output_image.save(bytes_io, format=extension, optimize=True) image_data.seek(0) image_data.file.write(bytes_io.getvalue()) image_data.file.truncate() elif OPTIMIZED_IMAGE_METHOD == 'tinypng': # disable warning info requests.packages.urllib3.disable_warnings() tinify.key = TINYPNG_KEY optimized_buffer = tinify.from_buffer( image_data.file.read()).to_buffer() image_data.seek(0) image_data.file.write(optimized_buffer) image_data.file.truncate() return image_data
def process_album(album_artist, album, songs): album_folder = '{base_dir}/{album_artist}/{album}'.format( base_dir=OUTDIR, album_artist=album_artist, album=album) if not os.path.exists(album_folder): os.makedirs(album_folder) print('{album_artist} > {album}'.format(album_artist=album_artist, album=album)) snagged_artwork = None converted_mp3s = [] for song in songs: if snagged_artwork is None: mut = File(get_full_path_from_song(song)) if 'covr' in mut.tags: if mut.tags['covr']: art = mut.tags['covr'][0] extn = 'jpg' if art.imageformat == 13 else 'png' with open( '{album_folder}/artwork.{extn}'.format( album_folder=album_folder, extn=extn), 'wb') as f: f.write(art) snagged_artwork = extn segment = AudioSegment.from_file(get_full_path_from_song(song)) mp3_path = '{album_folder}/{track_num}. {title}.mp3'.format( album_folder=album_folder, track_num=song.track_number, title=song.name.replace('/', '-')) converted_mp3s.append(mp3_path) segment.export(mp3_path, format='mp3', parameters=["-q:a", "0"], id3v2_version='3', tags={ 'artist': song.artist, 'album_artist': song.album_artist, 'album': song.album, 'disk': song.disc_number, 'title': song.name, 'track': song.track_number }) if snagged_artwork is not None: extracted = '{album_folder}/artwork.{extn}'.format( album_folder=album_folder, extn=snagged_artwork) processed = '{album_folder}/artwork_processed.jpg'.format( album_folder=album_folder) with open(extracted, 'rb') as f: artwork = Image.open(f) artwork = resizeimage.resize_thumbnail(artwork, [400, 400]) artwork.save(processed) for mp3_path in converted_mp3s: id3 = eyed3.load(mp3_path) id3.tag.images.set(3, open(processed, 'rb').read(), 'image/jpeg') id3.tag.save() os.remove(extracted) os.remove(processed)
canvasLog.create_text(500, 0, fill="white", font="Times 12", text=logs) scrollbar.config(command=canvasLog.yview) canvasLog.config(yscrollcommand=scrollbar.set) #scrollbarH = Scrollbar(canvasLog, orient=HORIZONTAL, command=canvasLog.yview) #scrollbarH.pack(side=BOTTOM, fill=X) #scrollbarH.config(command=canvasLog.xview) #canvasLog.config(xscrollcommand=scrollbarH.set) Label(Frame3, text="Simulation").pack(side=TOP, padx=80, pady=20) canvasSim = Canvas(Frame3, bg="White") img1 = Image.open('data/Prediction_Result_for_Monday.png') img1 = resizeimage.resize_thumbnail(img1, [800, 700]) img1.save('data/Prediction_Result_for_Monday.png', img1.format) img2 = Image.open('data/Prediction_nbCLient_for_Monday.png') img2 = resizeimage.resize_thumbnail(img2, [800, 700]) img2.save('data/Prediction_nbCLient_for_Monday.png', img2.format) img3 = Image.open('data/Prediction_Bandwidth_Mo.s_for_Monday.png') img3 = resizeimage.resize_thumbnail(img3, [800, 700]) img3.save('data/Prediction_Bandwidth_Mo.s_for_Monday.png', img3.format) img4 = Image.open('fleche.jpeg') img4 = resizeimage.resize_thumbnail(img4, [300, 200]) img4.save('fleche.jpeg', img4.format) img5 = Image.open('data/Prediction_Bandwidth_Mo.s_for_Tuesday.png')
from PIL import Image from resizeimage import resizeimage fd_img = open('views/images/pizzeria.jpg', 'r') img = Image.open(fd_img) img = resizeimage.resize_thumbnail(img, [100, 75]) img.save('views/images/pizzeria_min.jpg', img.format) fd_img.close() fd_img = open('views/images/pizzeria.jpg', 'r') img = Image.open(fd_img) img = resizeimage.resize_thumbnail(img, [720, 540]) img.save('views/images/pizzeria_min_lg.jpg', img.format) fd_img.close()
def img_smaller(filename): img = Image.open(open(filename, 'rb')) newsize = [img.size[0] * 0.9, img.size[1] * 0.9] smallerimg = resizeimage.resize_thumbnail(img, newsize) smallerimg.save(filename, smallerimg.format)