def __pic2array(self, filepath): if self.__type == 'directory': image = Image.open(filepath) elif self.__type == 'zip': __relativepath = self.__relativepath(filepath) image = Image.open(self.__archive.open(self.__archive.getinfo(__relativepath))) else: raise Exception("Unknown type") if self.__grayscale: return numpy.asarray(image.convert('L').resize((self.__width, self.__height))) else: raise Exception("loading image except for grayscale not supported yet...")
def select_image(index): # Disable scientific notation for clarity np.set_printoptions(suppress=True) # Load the model model = tf.contrib.lite.Interpreter(model_path="model_unquant.tflite") # Create the array of the right shape to feed into the keras model # The 'length' or number of images you can put into the array is # determined by the first position in the shape tuple, in this case 1. data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) # Replace this with the path to your image image = Image.open('image' + str(index) + '.jpg') #resize the image to a 224x224 with the same strategy as in TM2: #resizing the image to be at least 224x224 and then cropping from the center size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) #turn the image into a numpy array image_array = np.asarray(image) # display the resized image image.show() # Normalize the image normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1 # Load the image into the array data[0] = normalized_image_array # run the inference prediction = model.predict(data) print(prediction)
def getImage(): '''Asks the user for the image :return the image: ''' img_string = imageOpen.prompt_and_get_file_name() img = Image.open(img_string) return img
def is_valid_image_old(path): img = Image.open(path) try: img.verify() return img.format in ['JPEG', 'JPEG2000', 'PNG', 'GIF'] except Exception: return False
def tweet_image(message): font = ImageFont.truetype(font="PlainPensle_BoldItalic.ttf", size=75) W, H = (1280, 720) w, h = font.getsize(message) img = Image.new('RGB', (W, H), color=(240, 226, 179)) img_w, img_h = img.size draw = ImageDraw.Draw(img) draw.text(((W - w) / 2, 585), message, font=font, fill='black') img2 = Image.open( os.path.join("C:/Users/Matthew/PycharmProjects/TwitterBot/botImages", file), 'r') img2 = img2.resize((500, 500)) img3 = img2.convert("RGBA") img3.resize((500, 500)) offset = (390, 65) img.paste(img3, offset, mask=img3) img.save('temp.png') os.remove( os.path.join("C:/Users/Matthew/PycharmProjects/TwitterBot/botImages", file)) api.update_with_media('temp.png', status=message)
def avhash(im): if not isinstance(im, Image.Image): im = Image.open(im) im = im.resize((8, 8), Image.ANTIALIAS).convert('L') avg = reduce(lambda x, y: x + y, im.getdata()) / 64. return reduce(lambda x, (y, z): x | (z << y), enumerate(map(lambda i: 0 if i < avg else 1, im.getdata())), 0)
def main(): im = Image.open('dead_parrot.jpg') # Can be many different formats. pix = im.load() print im.size # Get the width and hight of the image for iterating over print pix[x, y] # Get the RGBA Value of the a pixel of an image pix[x, y] = value # Set the RGBA Value of the image (tuple) im.save('alive_parrot.png') # Save the modified pixels as .png
def save(self, *args, **kwargs): """ Create slug based on title If a zip file is uploaded, extract images from it and add them to the gallery. Removes zip file afterwards """ self.slug = slugify(self.title) super(BaseGallery, self).save(*args, **kwargs) if self.zip_import: zip_file = ZipFile(self.zip_import) for name in zip_file.namelist(): data = zip_file.read(name) try: # backwards compatibile with PIL from Pillow import Image image = Image.open(BytesIO(data)) image.load() image = Image.open(BytesIO(data)) image.verify() except ImportError: pass except: continue name = os.path.split(name)[1] # This is a way of getting around the broken nature of # os.path.join on Python 2.x. See also the comment below. if isinstance(name, bytes): encoding = charset_detect(name)['encoding'] tempname = name.decode(encoding) else: tempname = name # A gallery with a slug of "/" tries to extract files # to / on disk slug = self.slug if self.slug != "/" else "" path = os.path.join(UPLOAD_DIR, slug, tempname) saved_path = default_storage.save(path, ContentFile(data)) self.images.create(file=saved_path) zip_file.close() self.zip_import.delete(save=True)
def calculate_image_size(image): """Calculates width and height of image in pixels. Args: image as string (path to image). Returns: tuple (int image width in pixels, int image height in pixels). """ img = Image.open(image) # Pillow Image Class Method (open). return img.size # Pillow Image Class Attribute (size).
def handle_uploaded_file(f, name=None): if name is None: name = str(f) full_path = os.path.join(BASE_DIR, 'static', 'uploads', name) with open(full_path, 'w+b') as destination: for chunk in f.chunks(): destination.write(chunk) im = Image.open(full_path) img = im.resize((250, 250), Image.ANTIALIAS) imgIcon = im.resize((50, 50), Image.ANTIALIAS) img.save(full_path, 'PNG') imgIcon.save(full_path + 'tiny', 'PNG') return full_path
def create_thumbnail(self, size, force_crop=False): """ Creates a thumbnail for an image at the specified size """ if not size.auto_size: try: crop = self.get_crop(size) cropped_image = utils.create_cropped_image( self.image.path, crop.crop_x, crop.crop_y, crop.crop_w, crop.crop_h ) except Crop.DoesNotExist: # auto-crop if no crop is defined cropped_image = pil.open(self.image.path) else: cropped_image = pil.open(self.image.path) self.rescale(cropped_image=cropped_image, size=size, force_crop=force_crop)
def image_data(filename: str): """ return image data for filename """ try: im = Image.open(filename) except IOError: print("failed to identify", filename) else: print("image format:", im.format) print("image mode:", im.mode) print("image size:", im.size) if "description" in im.info: print("image description:", im.info["description"])
def make_thumbnail(old_path, new_path, f, w, h, quality): path = old_path + '/' + f # convert('RGB')这个必须加上, 否则可能会报错: cannot write mode P as JPEG icon = Image.open(path).convert('RGB') width, height = icon.size print width, height # 只切高度大于宽度的图片, 宽度大于高度的图片复制到另一个目录 if width < height: icon = icon.resize((500, int(500 * height / width)), Image.ANTIALIAS) else: icon = icon.resize((int(500 * width / height), 500), Image.ANTIALIAS) icon = icon.crop((0, 0, int(w), int(h))) print new_path + '/' + f icon.save(new_path + '/' + f, 'jpeg', quality=quality)
def convert_dir(in_dir, out_dir): if not os.path.exists(out_dir): os.system("mkdir -p " + out_dir) for img_file in tqdm.tqdm(os.listdir(in_dir)): img_path = os.path.join(in_dir, img_file) r_image = Image.open(img_path) c_image = ImageProcessor.resize_file( r_image, 32, 32 ).convert("RGBA") out_path = os.path.join(out_dir, img_file) c_image.save(out_path.split(".")[0] + ".png")
def create_cropped_image(path=None, x=0, y=0, width=0, height=0): """ Crop image given a starting (x, y) position and a width and height of the cropped area """ if path is None: raise ValueError("A path must be specified") img = Image.open(path) img.copy() img.load() img = img.crop((x, y, x + width, y + height)) img.load() return img
def is_img_uniform_size(self, img_content): """ 判断图片格式大小是否符合要求 :param img_content: Stream2bin 2进制流文件 :return: Boole True/False """ try: img = Image.open(io.BytesIO(img_content)) except: print 'Image.open io.BytesIO failed' return height, width = img.size img_flag = True if height < 150 or width < 150: img_flag = False return img_flag
def is_img_uniform_size(self, img_content, heigth=150, width=150): """ 判断图片格式大小是否符合要求 :param img_content: Stream2bin 2进制流文件 :return: Boole True/False """ try: img = Image.open(io.BytesIO(img_content)) except: print('Image.open io.BytesIO failed') return img_h, img_w = img.size img_flag = True if img_h < heigth or img_w < width: img_flag = False return img_flag
def _dump_image(x): (index, p_list) = x w_dir = os.path.join(out_dir, str(index)) if not os.path.exists(w_dir): os.system("mkdir -p " + w_dir) out_list = [] for r_path in p_list: name = ("-".join(r_path.split("-")[1:])).replace("/", "$") w_path = os.path.join(w_dir, name) image = Image.open(r_path) image.save(w_path) out_list.append(w_path) return out_list
def clean(self): """ Additional file validation for saving """ if self.image: # Check for valid file extension if os.path.splitext(self.image.name)[1] == '': raise ValidationError("Please make sure images have file extensions before uploading") # Check for valid file try: pil_image = pil.open(self.image) except: raise ValidationError("Unable to open image file") # Check for minimum size requirement if self.validate_image_size: for size in self.size_set.size_set.all().order_by("-width"): if size.width > pil_image.size[0] or size.height > pil_image.size[1]: raise ValidationError("Uploaded image (%s x %s) is smaller than a required thumbnail size: %s" % (pil_image.size[0], pil_image.size[1], size)) return super(Image, self).clean()
def __getitem__(self, idx): # load the image as a PIL Image img_dict = self.obj['images'][idx] image = Image.open(img_dict['file_name']) w, h = img_dict['width'], img_dict['height'] img_id = img_dict['id'] # load the bounding boxes as a list of list of boxes # in this case, for illustrative purposes, we use # x1, y1, x2, y2 order. anns = [ann for ann in obj['annotations'] if ann['image_id'] == img_id] boxes = [ann['bbox'] for ann in anns] boxes = [[x[1], x[0], x[3], x[2]] for x in boxes] labels = torch.tensor([ann['category_id'] for ann in anns]) masks = [ann['segmentation'] for ann in anns] for i, obj in enumerate(masks): for j, poly in enumerate(obj): for k in range(0, len(poly), 2): masks[i][j][k], masks[i][j][k + 1] = poly[k + 1], poly[k] # create a BoxList from the boxes boxlist = BoxList(boxes, image.size, mode="xyxy") # add the labels to the boxlist boxlist.add_field("labels", labels) boxlist.add_field("masks", SegmentationMask(masks, (w, h), mode='poly')) if self.transforms: image, boxlist = self.transforms(image, boxlist) # return the image, the boxlist and the idx in your dataset return image, boxlist, idx
def main(): username = request.form['username'] print(username) search_filter = "(&(cn=" + username + ")" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'panoramic_trekking_app.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?") from exc execute_from_command_line(sys.argv) #Open image using Image module im = Image.open("images/cuba.jpg") #Show actual Image im.show() #Show rotated Image im = im.rotate(45) im.show()
def get_merge_image(self, image_mix, location_list): im = image.open(image_mix) im_list_upper = [] im_list_down = [] for location in location_list: if location['y'] == -58: im_list_upper.append( im.crop((abs(location['x']), 58, abs(location['x']) + 10, 166))) if location['y'] == 0: im_list_down.append( im.crop( (abs(location['x']), 0, abs(location['x']) + 10, 58))) new_im = image.new('RGB', (260, 116)) x_offset = 0 for im in im_list_upper: new_im.paste(im, (x_offset, 0)) x_offset += im.size[0] x_offset = 0 for im in im_list_down: new_im.paste(im, (x_offset, 58)) x_offset += im.size[0] return new_im
def load_image(path): image = Image.open(path) plt.imshow(image) plt.title('Image loaded successfully') return image
def save(self, *args, **kwargs): changed_image = self.content != self.__original_image if not self.id and not self.pub_date: self.pub_date = datetime.datetime.today() crop_original = kwargs.get('crop_original', False) super(MediaContent, self).save(*args, **kwargs) self.mimetype = mimetypes.guess_type(self.content.path)[0] if self.mimetype: content_type = self.mimetype.replace('/', '_') else: # assume everything else is text/plain content_type = 'text_plain' i = self.content.name.rindex('/') thumbnail = u'%sthumbnail_%s' % (unicode( self.content.name[:i + 1]), unicode(self.content.name[i + 1:])) gallery = u'%sgallery_%s' % (unicode( self.content.name[:i + 1]), unicode(self.content.name[i + 1:])) orig = self.content.name if (not self.thumbnail or not self.gallery or changed_image) and content_type.split('_')[0] == 'image': img_path = self.content.path if content_type == 'image_svg+xml': try: from nebula.mediacontent import svg_to_png svg_to_png.convert(img_path, svg_to_png.new_name(img_path)) img_path = svg_to_png.new_name(img_path) self.content.name = self.content.name[: -3] + self.content.name[ -3:].replace( 'svg', 'png') except: pass image = Image.open(img_path) image = convert_to_rgb(image) image = crop_aspect(image, ratio=1.0) # hace el thumb image_thumb = resize(image.copy(), size=self.get_sizes()['thumb']) image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail)) self.thumbnail = thumbnail # guarda la imagen para gallery image_gallery = resize(image.copy(), size=self.get_sizes()['gallery']) image_gallery.save(os.path.join(settings.MEDIA_ROOT, gallery)) self.gallery = gallery # guarda la imagen al tamaño máximo if crop_original: image_normal = resize(image.copy(), size=self.get_sizes()['normal']) image_normal.save(os.path.join(settings.MEDIA_ROOT, orig)) elif (not self.thumbnail or not self.gallery or changed_image) and content_type == 'application_pdf': # Crea una imagen de la primer pagina de un PDF from subprocess import call cmd = "gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \ -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 \ -sOutputFile=%(fileout)s %(filein)s" filein = os.path.join(settings.MEDIA_ROOT, self.content.name) filejpg = self.content.name[:-3] + self.content.name[-3:].replace( 'pdf', 'jpg') fileout = os.path.join(settings.MEDIA_ROOT, filejpg) if not os.access(filein, os.R_OK): raise 'not access %s' % filein files = { 'filein': filein.replace(' ', '\ '), 'fileout': fileout.replace(' ', '\ '), } # devuelve 0 si esta OK if not call(cmd % files, shell=True): i = filejpg.rindex('/') thumbnail = u'%sthumbnail_%s' % (unicode( filejpg[:i + 1]), unicode(filejpg[i + 1:])) gallery = u'%sgallery_%s' % (unicode( filejpg[:i + 1]), unicode(filejpg[i + 1:])) image = Image.open(fileout) image = convert_to_rgb(image) #image = crop_aspect(image, ratio=1.0) # hace el thumb image_thumb = resize(image.copy(), size=None, max_width=self.get_sizes()['gallery'][0]) image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail)) self.thumbnail = thumbnail # guarda la imagen para gallery #image_gallery = image.copy() image_gallery = resize(image.copy(), size=None, max_width=self.get_sizes()['normal'][0]) image.save(os.path.join(settings.MEDIA_ROOT, gallery)) self.gallery = gallery # borra la original porque es un PDF try: os.remove(fileout) except (OSError, ValueError): pass super(MediaContent, self).save(*args, **kwargs)
from Pillow import Image import glob, os for infile in glob.glob('c:/Users/guest/Desktop/cards/*.jpg'): source = Image.open(infile) o1 = source.crop((85, 20, 772, 1009)) o2 = source.crop((771, 20, 1458, 1009)) o_path = 'c:/Users/guest/Desktop/o_cards/' name = os.path.basename(infile) o1.save(o_path + name + ".card1.jpg") o2.save(o_path + name + ".card2.jpg")
from tkinter import * from Pillow import ImageTk, Image root = Tk() root.title('Codemy.com Image Viewer') root.iconbitmap('c:/gui/codemy.ico') my_img1 = ImageTk.PhotoImage(Image.open("images/aspen.png")) my_img2 = ImageTk.PhotoImage(Image.open("images/aspen2.png")) my_img3 = ImageTk.PhotoImage(Image.open("images/me1.png")) my_img4 = ImageTk.PhotoImage(Image.open("images/me2.png")) my_img5 = ImageTk.PhotoImage(Image.open("images/me3.png")) image_list = [my_img1, my_img2, my_img3, my_img4, my_img5] status = Label(root, text="Image 1 of " + str(len(image_list)), bd=1, relief=SUNKEN, anchor=E) my_label = Label(image=my_img1) my_label.grid(row=0, column=0, columnspan=3) def forward(image_number): global my_label global button_forward global button_back my_label.grid_forget()
import numpy as np #from PIL import Image from Pillow import Image from timeit import default_timer as timer import matplotlib.pyplot as plt import matplotlib.patches as patches from ModelLoader import ModelLoader from PostProcessor import PostProcessor from preprocess import PreProcessor import json model_loader = ModelLoader() img = Image.open('/home/bilal/Downloads/foto_van_yosra1.jpg') # print("---------------------------------") # print("0 for tinyYolo") # val = input("give your neural network architecture type: ") preprocessor = PreProcessor(0, img) img_data = preprocessor.preprocess() # print("---------------------------------------------") # load a simple model session = model_loader.load_session(1) begin = timer() # see the input name and shape input_name = session.get_inputs()[0].name """# print("input name = ", input_name) input_shape = session.get_inputs()[0].shape
time_start = time.time() # Data descramblng for idx in range(rx_data_size): rx_data_buff[idx] = rx_data_buff[idx] ^ SCRAMBLE_SEQ # Write data to file with open(TEMP_FILE_PATH, 'wb') as temp_file: temp_file.write(rx_data_buff[0:rx_data_size]) # Format and vizualize data try: rx_data_img = imageio.imread(TEMP_FILE_PATH).astype(np.uint8) if rx_data_img.ndim == 2: plt.imshow(rx_data_img, cmap='gray') else: plt.imshow(rx_data_img) plt.show() plt.pause(0.001) except: print('RX DATA CORRUPT ...') image = Image.open(TEMP_FILE_PATH) image.show #os.system('gpicview -single-window %s &' % TEMP_FILE_PATH) time_elapsed = (time.time() - time_start) print('time for image plot %f ' % time_elapsed)
from Tkinter import * import tkMessageBox import Tkinter from Pillow import ImageTk, Image root = Tkinter.Tk() root.title("Qweet") root.geometry("500x300") img = ImageTk.PhotoImage(Image.open("QweetsLogo.png")) imglabel = Label(app_root, image=img).grid(row=1, column=1) Lbl1 = Label(root, text="Input username here (ommit the @):") Lbl1.pack(side=TOP,padx=5,pady=5) Entry1 = Entry(root, bd =1) Entry1.pack(side=TOP,padx=5,pady=5) Lbl2 = Label(root, text="Input a tweet ID here:") Lbl2.pack(side=TOP,padx=5,pady=5) Entry2 = Entry(root, bd =1) Entry2.pack(side=TOP,padx=5,pady=5) Lbl3 = Label(root, text="Input a Keyword here:") Lbl3.pack(side=TOP,padx=5,pady=5) Entry3 = Entry(root, bd =1) Entry3.pack(side=TOP,padx=5,pady=5) def PrintCommand(): reply = str(Entry1.get()) replyID = str(Entry2.get()) keyword = str(Entry3.get())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #' a test module ' __author__='ZhangLei' #类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名 #类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc等 #定义为私有的函数 def _private_1(name): return 'Hello, %s' % name def _private_2(name): return "Hello,%s" % name; def greeting(name): if(len(name) > 3): return _private_1(name); else: return _private_2(name); print(greeting("hello")) #模块 #安装模块 #pip install Pillow from Pillow import Image; im = Image.open("test.png"); print(im.format,im.size,im.mode); im.thumbnail(200,100); im.save("test_thumbnail.jpg","JPEG");
def save(self, *args, **kwargs): changed_image = self.content != self.__original_image if not self.id and not self.pub_date: self.pub_date = datetime.datetime.today() crop_original = kwargs.get('crop_original', False) super(MediaContent, self).save(*args, **kwargs) self.mimetype = mimetypes.guess_type(self.content.path)[0] if self.mimetype: content_type = self.mimetype.replace('/', '_') else: # assume everything else is text/plain content_type = 'text_plain' i = self.content.name.rindex('/') thumbnail = u'%sthumbnail_%s' % (unicode(self.content.name[:i+1]), unicode(self.content.name[i+1:])) gallery = u'%sgallery_%s' % (unicode(self.content.name[:i+1]), unicode(self.content.name[i+1:])) orig = self.content.name if (not self.thumbnail or not self.gallery or changed_image) and content_type.split('_')[0]=='image': img_path = self.content.path if content_type == 'image_svg+xml': try: from nebula.mediacontent import svg_to_png svg_to_png.convert(img_path, svg_to_png.new_name(img_path)) img_path = svg_to_png.new_name(img_path) self.content.name = self.content.name[:-3] + self.content.name[-3:].replace('svg', 'png') except: pass image = Image.open(img_path) image = convert_to_rgb(image) image = crop_aspect(image, ratio=1.0) # hace el thumb image_thumb = resize(image.copy(), size=self.get_sizes()['thumb']) image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail)) self.thumbnail = thumbnail # guarda la imagen para gallery image_gallery = resize(image.copy(), size=self.get_sizes()['gallery']) image_gallery.save(os.path.join(settings.MEDIA_ROOT, gallery)) self.gallery = gallery # guarda la imagen al tamaño máximo if crop_original: image_normal = resize(image.copy(), size=self.get_sizes()['normal']) image_normal.save(os.path.join(settings.MEDIA_ROOT, orig)) elif (not self.thumbnail or not self.gallery or changed_image) and content_type == 'application_pdf': # Crea una imagen de la primer pagina de un PDF from subprocess import call cmd = "gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \ -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 \ -sOutputFile=%(fileout)s %(filein)s" filein = os.path.join(settings.MEDIA_ROOT, self.content.name) filejpg = self.content.name[:-3] + self.content.name[-3:].replace('pdf', 'jpg') fileout = os.path.join(settings.MEDIA_ROOT, filejpg) if not os.access(filein, os.R_OK): raise 'not access %s' % filein files = { 'filein': filein.replace(' ', '\ '), 'fileout': fileout.replace(' ', '\ '), } # devuelve 0 si esta OK if not call(cmd % files, shell=True): i = filejpg.rindex('/') thumbnail = u'%sthumbnail_%s' % (unicode(filejpg[:i+1]), unicode(filejpg[i+1:])) gallery = u'%sgallery_%s' % (unicode(filejpg[:i+1]), unicode(filejpg[i+1:])) image = Image.open(fileout) image = convert_to_rgb(image) #image = crop_aspect(image, ratio=1.0) # hace el thumb image_thumb = resize(image.copy(), size=None, max_width=self.get_sizes()['gallery'][0]) image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail)) self.thumbnail = thumbnail # guarda la imagen para gallery #image_gallery = image.copy() image_gallery = resize(image.copy(), size=None, max_width=self.get_sizes()['normal'][0]) image.save(os.path.join(settings.MEDIA_ROOT, gallery)) self.gallery = gallery # borra la original porque es un PDF try: os.remove(fileout) except (OSError, ValueError): pass super(MediaContent, self).save(*args, **kwargs)
def _generate_thumbnail(self, video, thumbnail_width, thumbnail_height, crop=True, frames=100): histogram_list = [] framw_average = [] path, full_filename = os.path.split(self.path) filename, extension = os.path.splitext(full_filename) # By default temp frame data is stroed under MEDIA_ROOT/temp path = '%s/temp/' % settings.MEDIA_ROOT if not os.path.isdir(path): os.mkdir(path) hashable_value = '%s%s' % (full_filename, int(time.time())) filehash = hashlib.md5(hashable_value).hexdigest() frame_args = {'path': path, 'filename': filehash, 'frame': '%d'} frame = '%(path)s%(filename)s.%(frame)s.jpg' % frame_args # Build the ffmpeg shell command and run it via subprocess cmd_args = {'frames': frames, 'video_path':video_path, 'output':frame} command = 'ffmpeg -i %(video_path)s -y -vframes %(frames)d %(output)s' command = command % cmd_args response = subprocess.call(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Fail silently if ffmpeg is not installed. if reponse != 0: return # Loop through the generated images, open, and generate the image histogram for index in range(1, frames+1): frame_name = frame % index # If for some reason the frame does not exist, go to next frame. if not os.path.exists(frame_name): continue image = Image.open(frame_name) # Convert to RGB if necessary if image.mode not in ('L', 'RGB'): image = image.convert(image.histogram()) frames = len(histogram_list) # Calculate the accumulated average for idx in range(len(histogram_list[0])): average = 0.0 accumulation = 0.0 for idy in range(frames): accumulation += histogram_list[idy][idx] average = (float(accumulation) / frames) frame_average.append(average) minn = -1 minRMSE = -1 # Calculate the mean squared error for idx in range(frames): results = 0.0 average_count = len(frame_average) for idy, average in enumerate(frame_average): error = average - float(histogram_list[idx][idy]) results += float((error*error)) / average_count rmse = math.sqrt(results) if minn == -1 or rmse < minRMSE: minn = (idx + 1) minRMSE = rmse frame_path = frame % (minn) image = Image.open(frame_path) # Crop the image if auto_crop is enabled and dimensions are the same. if thumbnail_width == thumbnail_height and self.auto_crop: width, height = image.size min_size = min(width, height) new_width = (width - min_size) / 2 new_height = (height - min_size) / 2 params = ( new_width, new_height, width - new_width, height - new_height ) image2 = image.crop(params) image2.load() image2.thumbnail((thumbnail_width, thumbnail_height), Image.ANTIALIAS) else: image2 = image image2.thumbnail((thumbnail_width, thumbnail_height), Image.ANTIALIAS) io = cStringIO.StringIO() image2.save(io, 'jpeg') # Unlink the temp files. for idx in range(frames): frame_fiel = frame % (idx + 1) os.unlink(frame_file) return ContentFile(io.getvalue())
def showImg(self): load = Image.open('Aaron.jpg') render = ImageTk.PhotoImage(load) img = Label(self, image=render) img.image = render img.place(x=0, y=0)
import _init_paths from imagelib import crop_center, crop_max_square, expand2square, mask_circle_solid, mask_circle_transparent import os import glob from Pillow import Image, ImageDraw, ImageFilter im = Image.open('Images/3d0a1da004d0e27c1784743b3297106a.jpg') thumb_width = 150 # ![lena](data/src/lena.jpg) im_thumb = crop_center(im, thumb_width, thumb_width) im_thumb.save('Images/_thumbnail_center_square.jpg', quality=95) # ![lena_thumbnail_center_square](data/dst/lena_thumbnail_center_square.jpg) im_thumb = crop_max_square(im).resize((thumb_width, thumb_width), Image.LANCZOS) im_thumb.save('Images/_thumbnail_max_square.jpg', quality=95) # ![lena_thumbnail_max_square](data/dst/lena_thumbnail_max_square.jpg) im_thumb = expand2square(im, (0, 0, 0)).resize((thumb_width, thumb_width), Image.LANCZOS) im_thumb.save('Images/_thumbnail_expand.jpg', quality=95) # ![lena_thumbnail_expand](data/dst/lena_thumbnail_expand.jpg) im_square = crop_max_square(im).resize((thumb_width, thumb_width), Image.LANCZOS) im_thumb = mask_circle_solid(im_square, (0, 0, 0), 4)
from tkinter import * from Pillow import ImageTk, Image import os import tkinter as tk import tkinter.messagebox as myMs file_open = tk.Tk() file_open.title('My First Window') img = ImageTk.PhotoImage(Image.open("E:\\Passport.jpg")) panel = Label(root, image=img) panel.pack(side="bottom", fill="both", expand="yes") def myMessage(): myMs.showinfo('hello', 'kina click gareko') my_btn = tk.Button(file_open, text='click button', command=myMessage) my_btn.pack() my_can = tk.Canvas(width=500, height=600, bg='white') my_can.pack() file_open.mainloop()
#!/usr/bin/env python #coding: utf-8 myPath = "C:\\Users\\Lenovo\\Desktop\\" fontPath = "C:\\Windows\\Fonts\\" #win10上系统的字体位置 inputFile = "1_sirwill.jpg" outputFile = "output.jpg" from Pillow import Image, ImageDraw,ImageFont #打开图片 im = Image.open(myPath + inputFile) #打开一个照片对象 draw = ImageDraw.Draw(im) #创建画布 #根据图片大小确定字体大小 fontsize = (min(im.size)/4 #注意truetype方法要整数,需要取整 #加文字 #实例 font = ImageFont.truetype(fontPath + 'ALGER.TTF',fontsize) #其余参数默认 得到字体实例 draw.text((im.size[0]-fontsize,0), '5', font = font, fill = (256, 0, 0)) #确定位置、数字、实例、填充色 #保存图片 im.save(myPath + outputFile,"jpeg")
def openImage(self): try: self.img = Image.open(f"./images/{self.name}") except: print("Wrong file name") exit(1)