def make_imageresize(file_path, extension='.jpg'): """Resize images for standardized instagram posting and overwrite their. Args: file_path(str): image file location extension(str): image file extension """ gorizontal = [1080, 565] vertical = [600, 750] quadrate = [gorizontal[0], gorizontal[0]] if get_file_extension(file_path) == extension: fd_img = open(file_path, 'rb') img = Image.open(fd_img) try: if img.width > img.height: img = resizeimage.resize_contain(img, gorizontal) elif img.width == img.height: img = resizeimage.resize_contain(img, quadrate) else: img = resizeimage.resize_contain(img, vertical) except resizeimage.ImageSizeError: logging.info('ImageSizeError' + img) if img.mode in ("RGBA", "P"): img = img.convert("RGB") img.save(file_path, img.format) fd_img.close() else: pass
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 compute_similarities(event_users, photo_target): photo_target = BytesIO(photo_target) with Image.open(photo_target) as image: width, height = image.size imageB = resizeimage.resize_contain( image, [int(0.5 * width), int(0.5 * height)]) imageB.save("imageB.png") unknown_picture = face_recognition.load_image_file("imageB.png") if len(face_recognition.face_encodings(unknown_picture)) > 0: unknown_face_encoding = face_recognition.face_encodings( unknown_picture)[0] for stored_user in event_users: url_stored = stored_user['userInfo']['photo'] stored_file = BytesIO(urllib.urlopen(url_stored).read()) with Image.open(stored_file) as image: width, height = image.size imageA = resizeimage.resize_contain( image, [int(0.5 * width), int(0.5 * height)]) imageA.save("imageA.png") known_picture = face_recognition.load_image_file("imageA.png") known_face_encoding = face_recognition.face_encodings( known_picture)[0] distance = face_recognition.face_distance([known_face_encoding], unknown_face_encoding)[0] stored_user['score'] = 1 - distance return True else: return False
def transform_images(image_names, path_to_dataset: str = '.'): for image_name in image_names: path = pathlib.Path(f'{path_to_dataset}/{image_name}.ppm') with open(path, 'r+b') as file: with Image.open(file) as image: cover = resizeimage.resize_contain(image, [700, 700]) cover = resizeimage.resize_contain(cover, [256, 256]) cover.save(f'./transformed/{image_name}.png')
def resizeSignature(nameSignature, train=True, genuine=True): if train and genuine: with open(nameSignature, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_contain(image, [500, 300]).convert('L') cover = np.asanyarray(cover) #cover = scipy.misc.imresize(image, (500,500), map()ode='L') elif train and not genuine: with open(nameSignature, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_contain(image, [500, 300]).convert('L') cover = np.asanyarray(cover) return cover
def signUp(): """ Sign UP function if there is no third party account. Stores the credentials in database. """ users = session.query(User).all() if 'email' in request.form and request.method == 'POST': email = request.form['email'] if request.form['email'] in [user.email for user in users]: flash('{} is already is registred!'.format(email)) return render_template('signup.html') else: flash('Please provide your email address!') return render_template('signup.html') if 'file' not in request.files and 'image' in request.files: image = request.files['image'] if image.filename != '' and allowed_file(image.filename): filename = secure_filename(image.filename) if ( image.filename in [user.image.split('/')[-1] for user in users] ): flash('{} picture name already exists!'.format(image.filename)) return render_template('signup.html') image_resize = Image.open(image) image_resize = resizeimage.resize_contain(image_resize, [200, 200]) image_resize.save(os.path.join( app.config['UPLOAD_FOLDER'], filename ), image_resize.format) image_path = 'item_images/' + filename else: image_path = 'profile_images/profile.png' else: image_path = 'profile_images/profile.png' if 'username' in request.form: username = request.form['username'] if username in [user.name for user in users]: flash('{} user name already exists!'.format(username)) return render_template('signup.html') else: flash('Please choose a user name!') return render_template('signup.html') if 'password1' in request.form and 'password2' in request.form: password1 = request.form['password1'] password2 = request.form['password2'] if password1 != password2: flash('The password does not match') return render_template('signup.html') else: flash('Please choose a password!') return render_template('signup.html') user = User(name=username, email=email, image=image_path) user.hash_password(password1) session.add(user) session.commit() return redirect(url_for('showLogin'))
def read_jpg(filepath, weight, height, name): image = im.open(filepath) image = ri.resize_contain(image, [weight,height]) image=image.convert('RGB') #image.save('/home/lukasz/Downloads/tmp/'+name) image = np.array(image) return image
def feeder(): counter = 0 while len(pics)>=4: corners = CORNERS[:] print corners canvas = Image.new('RGBA', (CANVAS_X, CANVAS_Y)) # Here the four pictures will be rezised to fit the canvas for x in range(0,4): pic = Image.open(pics.pop(0)) if pic.height > pic.width: pic = pic.rotate(90, expand = 1) #CHECK IF THE PICTURE PASSES THE SIZE REQUIREMENT, IF SO RUNS RESIZEIMAGE if pic.size[0] >= CANVAS_X/2: pic = resizeimage.resize_contain(pic,[CANVAS_X/2, CANVAS_Y/2]) #IF THE REQUIREMENT IS NOT MET, THE PICTURE WILL BE UPSCALED else: if pic.height == pic.width or pic.height/CANVAS_Y > pic.width/CANVAS_Y: baseheight = CANVAS_Y/2 wpercent = (baseheight/float(pilt.size[0])) hsize = int((float(pic.size[1])*float(wpercent))) pic = pic.resize((baseheight,hsize), PIL.Image.ANTIALIAS) else: basewidth = CANVAS_X/2 wpercent = (basewidth/float(pic.size[0])) hsize = int((float(pic.size[1])*float(wpercent))) pic = pic.resize((basewidth,hsize), PIL.Image.ANTIALIAS) canvas.paste(pic, corners.pop(0)) canvas.save('/tmp/collab{0}.jpg'.format(counter)) counter += 1 print canvas
def resize_img(self, filename: str, size: Tuple[int, int] = (299, 299)): """ Resizes the image using padding :param filename: :param size: """ img = Image.open(join(self.source_dir, filename)) width, height = img.size orig_shape = np.array(img.size) wanted_shape = np.array(size) ratios = wanted_shape / orig_shape wanted_width, wanted_height = size ratio_w, ratio_h = wanted_width / width, wanted_height / height if np.alltrue(ratios > 1): # Both sides of the image are shorter than the desired dimension, # so take the side that's closer in size and enlarge the image # in both directions to make that one fit factor = min(ratio_h, ratio_w) img = img.resize((int(width * factor), int(height * factor))) # Now we have an image that's either larger than the desired shape # or at least one side matches the desired shape and we can resize # with contain cover = resizeimage.resize_contain(img, size) cover.save(join(self.dest_dir, filename), 'JPEG')
def resize_images(images, width, height): """ Resize images This should keep the aspect ratio of the images """ all_images = [] for image in images: try: fd_img = open(image, "rb") except Exception as err: _LOGGER.error("Error attempting to open image %s: %s", str(image), str(err)) continue try: img = Image.open(fd_img) except Exception as err: _LOGGER.error("Error attempting to read image %s: %s", str(image), str(err)) continue img = resizeimage.resize_contain(img, [width, height]) pre, ext = os.path.splitext(image) image = pre + ".gif" img.save(image, img.format) fd_img.close() all_images.append(image) return all_images
def save(self, force_resize=False, *args, **kwargs): if (self.pk is None and self.image) or force_resize: try: image = Image.open(self.image) if _decompression_bomb_check(image): raise ValidationError("Invalid image") except IOError: return super(ResizeUploadedImage, self).save(*args, **kwargs) if image.format == 'PNG': max_square = getattr(settings, 'IMAGE_FIELD_MAX_PX', 400) smaller_than_canvas = \ (image.width < max_square and image.height < max_square) if smaller_than_canvas: max_square = (image.width if image.width > image.height else image.height) new_image = resize_contain(image, (max_square, max_square)) byte_string = io.BytesIO() new_image.save(byte_string, 'PNG') self.image = InMemoryUploadedFile(byte_string, None, self.image.name, 'image/png', byte_string.tell(), None) return super(ResizeUploadedImage, self).save(*args, **kwargs)
def resize_images(images: list, width: int, height: int) -> list: """Resize images. This should keep the aspect ratio of the images Returns list of images """ all_images = [] for image in images: try: with open(image, "rb") as fd_img: try: img = Image.open(fd_img) img = resizeimage.resize_contain(img, [width, height]) pre = os.path.splitext(image)[0] image = pre + ".gif" img.save(image, img.format) fd_img.close() all_images.append(image) except Exception as err: _LOGGER.error("Error attempting to read image %s: %s", str(image), str(err)) continue except Exception as err: _LOGGER.error("Error attempting to open image %s: %s", str(image), str(err)) continue return all_images
def get_document_pages(document_content_encoded: str) -> List[bytes]: # decode the content of the document document_content = b64decode(document_content_encoded) # extract the PDF file pdf = open_pdf(stream=document_content, filetype="pdf") # convert PDF document to PNG images (bytes) images_original = (page.getPixmap().getPNGdata() for page in pdf) # reduce size of each image to fit the max width and max height images_reduced = [] for image_original in images_original: # prepare streams of data image_original_stream = BytesIO(image_original) image_reduced_stream = BytesIO() # convert original image stream to PIL image format image_original_pil = Image.open(image_original_stream) # resize the image to fit image_reduced_pil = resize_contain(image_original_pil, [ settings.RENDERING_PNG_MAX_WIDTH, settings.RENDERING_PNG_MAX_HEIGHT ]) # convert the resized PIL image back to stream and then back to bytes image_reduced_pil.save(image_reduced_stream, format='PNG') image_reduced = image_reduced_stream.getvalue() # add to the list of converted pages images_reduced.append(image_reduced) return images_reduced
def check_fire(image_url): image_reduce_shape = 144 # Open file and preprocess img = Image.open(image_url) img_resized = np.array(img) img_grey = rgb2grey(img_resized) img_shape = np.shape(img_grey) img_shape = img_shape == (image_reduce_shape, image_reduce_shape) if not img_shape: img = Image.open(image_url) img_resized = resizeimage.resize_contain( img, [image_reduce_shape, image_reduce_shape]) img_resized = np.array(img_resized) img_grey = rgb2grey(img_resized) img_grey = img_grey.reshape(1, image_reduce_shape * image_reduce_shape) # load model #pkl_filename = 'fire_predictor_model.pkl' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) IMG_DETECTOR = os.path.join(BASE_DIR, 'imgdetector') pkl_filename = IMG_DETECTOR + '/fire_predictor_model.pkl' with open(pkl_filename, 'rb') as file: model = pickle.load(file) prediction = model.predict(img_grey) if prediction[0] == 1.0: return True else: return False
def process_image(photo, uid): if imghdr.what(photo): key = 'jpegPhoto' account = ldap_get_member(uid) image = Image.open(photo) icon = resizeimage.resize_contain(image, [300, 300]) icon = icon.convert("RGB") bin_icon = io.BytesIO() icon.save(bin_icon, format='JPEG') con = _ldap.get_con() exists = account.jpegPhoto if not exists: ldap_mod = ldap.MOD_ADD else: ldap_mod = ldap.MOD_REPLACE mod = (ldap_mod, key, bin_icon.getvalue()) mod_attrs = [mod] con.modify_s(account.get_dn(), mod_attrs) return True else: return False
def FER2013_Testing_Set(self): Testing_labels = [] Testing_Images = [] path = self.path + 'FER2013-Testing.csv' with open(path) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') #row[0] = Labels, row[1] = Image Pixels c = 0 for row in readCSV: Label = [0] * 7 Label[int(row[0])] = 1 Testing_labels.append(Label) image = row[1].split() #Cast strings to integer image = [int(i) for i in image] #Convert 1D array to 2D array 48x48 Image48x48 = np.reshape(image, (48, 48)) #Convert 2D array to Image Image42x42 = Image.fromarray(np.uint8(Image48x48)) #Resize Image to 42x42 Image42x42 = resizeimage.resize_contain(Image42x42, [42, 42]) #Convert Image to 2D array Image42x42 = np.uint8(Image42x42.convert('L')) Testing_Images.append(Image42x42) c = c + 1 if c >= 400: break return Testing_labels, Testing_Images
async def create_listing(db: Session = Depends(get_db), user: schemas.User = Depends(get_current_user), name: str = Form(...), price: int = Form(...), category: str = Form(...), course: Optional[str] = Form(None), description: str = Form(...), images: List[UploadFile] = File(...)): # create new listing object listing = schemas.Listing(name=name, description=description, price=price, seller_id=user.id, course=course) photoPaths = [] for file in images: # create random file names for image and thumbnail imgName = str(uuid.uuid4()) thmbName = str(uuid.uuid4()) fileType = '.png' # construct file paths imgPath = "/images/" + imgName + fileType thmbPath = "/images/" + thmbName + fileType photoPaths.append((imgPath, thmbPath)) # save as full-sized image img = Image.open(file.file) img.save(imgPath, img.format) # save as thumbnail img = resizeimage.resize_contain(img, [256, 256], bg_color=(0, 0, 0, 0)) img.save(thmbPath, img.format) img.close() return crud.create_listing(db, listing, photoPaths, category)
def save(self, *args, **kwargs): if self.pk is None and self.image: try: image = Image.open(self.image) except IOError: return super(ResizeUploadedImage, self).save(*args, **kwargs) if image.format == 'PNG': max_square = getattr(settings, 'IMAGE_FIELD_MAX_PX', 400) smaller_than_canvas = \ (image.width < max_square and image.height < max_square) if smaller_than_canvas: max_square = (image.width if image.width > image.height else image.height) new_image = resize_contain(image, (max_square, max_square)) byte_string = StringIO.StringIO() new_image.save(byte_string, 'PNG') self.image = InMemoryUploadedFile(byte_string, None, self.image.name, 'image/png', byte_string.len, None) return super(ResizeUploadedImage, self).save(*args, **kwargs)
def resize_img(self, filename: str, size: Tuple[int, int] = (299, 299)): """ Resizes the image using padding :param filename: :param size: """ img = Image.open(join(self.source_dir, filename)) orig_width, orig_height = img.size wanted_width, wanted_height = size ratio_w, ratio_h = wanted_width / orig_width, wanted_height / orig_height enlarge_factor = min(ratio_h, ratio_w) if enlarge_factor > 1: # Both sides of the image are shorter than the desired dimension, # so take the side that's closer in size and enlarge the image # in both directions to make that one fit enlarged_size = (int(orig_width * enlarge_factor), int(orig_height * enlarge_factor)) img = img.resize(enlarged_size) # Now we have an image that's either larger than the desired shape # or at least one side matches the desired shape and we can resize # with contain res = resizeimage.resize_contain(img, size).convert('RGB') res.save(join(self.dest_dir, filename), res.format)
def Open(event): """ action, that loads image, calls network function, that generates caption and shows image and caption in the box """ ftypes = [('JPEG files', '*.jpg'), ('All files', '*')] dlg = tkFileDialog.Open(filetypes=ftypes) fl = dlg.show() img_op = Image.open(fl) img_op = resizeimage.resize_contain(img_op, [400, 400]) img = ImageTk.PhotoImage(img_op) outp = Net.make_caption(fl) label1 = Label(root, image=img) label1.image = img label2 = Label(root, font="helvetica 18") label3 = Label(root, font="helvetica 15") label4 = Label(root, font="helvetica 15") label5 = Label(root, font="helvetica 15") label2["text"] = "Captions:" label3["text"] = outp[0] label4["text"] = outp[1] label5["text"] = outp[2] label1.place(x=10, y=50) label2.place(x=450, y=150) label3.place(x=450, y=200) label4.place(x=450, y=250) label5.place(x=450, y=300)
def FER2013_Training_Set(self): path = self.path + 'FER2013-Training.csv' Training_labels = [] Training_Images = [] with open(path) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') #row[0] = Labels, row[1] = Image Pixels for row in readCSV: Label = int(row[0]) #Label = [0] * 7 #Label[int(row[0])] = 1 Training_labels.append(Label) image = row[1].split() #Cast strings to integer image = [int(i) for i in image] #Convert 1D array to 2D array 48x48 Image48x48 = np.reshape(image, (48, 48)) #Convert 2D array to Image Image90x90 = Image.fromarray(np.uint8(Image48x48)) #Resize Image to 90x90 Image90x90 = resizeimage.resize_contain(Image90x90, [90, 90]) #Convert Image to 2D array Image90x90 = np.uint8(Image90x90.convert('L')) Training_Images.append(Image90x90) return Training_labels, np.array(Training_Images)
def savePicture(file, id): ''' Resize and save an uploaded picture for an item into static folder and return the filename of the picture. ''' extension = file.filename.rsplit('.', 1)[1] if extension.lower() not in ALLOWED_EXTENSIONS: flash("Unable to save uploaded picture.") return "" # Make filename unique and secure filename = str(id)+"_"+secure_filename(file.filename) uploaded_file = os.path.join(app.config['UPLOAD_FOLDER'],"u_"+filename) # First save the original uploaded picture in upload_folder file.save(uploaded_file) try: # Try to resize the picture fd_img = open(uploaded_file, 'r') img = Image.open(fd_img) img = resizeimage.resize_contain(img, [400, 300]) img.save(os.path.join(app.config['UPLOAD_FOLDER'],filename), img.format) fd_img.close() os.remove(uploaded_file) except: # Could not resize, just use the uploaded file instead os.rename(uploaded_file, os.path.join(app.config['UPLOAD_FOLDER'], filename)) return filename
def addBook(genre_id): """ This method adds a new book to the catalog. It takes given image and resize it to thumbanil size and saves it in the given folder. """ if 'username' not in login_session: return redirect(url_for('showLogin')) else: if request.method == 'POST': if request.form['name'] and request.form['price']: newbook = Book(name = request.form['name'], description = request.form['description'], price = request.form['price'], genre_id = genre_id, user_id=login_session.get('user_id') ) file = request.files['picture'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) with Image.open(file) as image: image = resizeimage.resize_contain(image, [100, 150]) image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) newbook.picture = filename session.add(newbook) session.commit() flash("New book added successfully!!") return redirect(url_for('displayBooks', genre_id = genre_id)) else: return render_template('addBook.html', genre_id = genre_id, login_session = login_session)
def FER2013_Validation_Set (self): Validation_labels = [] Validation_Images = [] path = self.path + 'FER2013-Validation.csv' with open(path) as csvfile: readCSV = csv.reader(csvfile, delimiter = ',') #row[0] = Labels, row[1] = Image Pixels for row in readCSV: Label = int(row[0]) #Label = [0] * 7 #Label[int(row[0])] = 1 Validation_labels.append(Label) image = row[1].split() #Cast strings to integer image = [int(i) for i in image] #Convert 1D array to 2D array 48x48 Image48x48 = np.reshape(image, (48, 48)) #Convert 2D array to Image Image84x84 = Image.fromarray(np.uint8(Image48x48)) #Resize Image to 84x84 Image84x84 = resizeimage.resize_contain(Image84x84, [84, 84]) #Convert Image to 2D array Image84x84 = np.uint8(Image84x84.convert('L')) Validation_Images.append(Image84x84) return Validation_labels, np.array(Validation_Images)
def resize_img(self, filename, size=(299, 299)): """Resize image using padding. Resized image is stored in `dest_dir`. Args: filename (str): Filename of specific image. size (Tuple[int, int], optional): Output image shape. Defaults to (299, 299). """ img = Image.open(join(self.source_dir, filename)) orig_width, orig_height = img.size wanted_width, wanted_height = size ratio_w, ratio_h = wanted_width / orig_width, wanted_height / orig_height enlarge_factor = min(ratio_h, ratio_w) if enlarge_factor > 1: # Both sides of the image are shorter than the desired dimension, # so take the side that's closer in size and enlarge the image # in both directions to make that one fit enlarged_size = ( int(orig_width * enlarge_factor), int(orig_height * enlarge_factor), ) img = img.resize(enlarged_size) # Now we have an image that's either larger than the desired shape # or at least one side matches the desired shape and we can resize # with contain res = resizeimage.resize_contain(img, size).convert("RGB") res.save(join(self.dest_dir, filename), res.format)
def resize_file(in_file): fd_img = open(in_file, 'r') img = Image.open(fd_img) img = resizeimage.resize_contain(img, [299, 299]) # img.save('google-image-0504-resized.jpeg', img.format) img.save((in_file.rsplit(".", 1)[0]) + '-resized.jpeg', img.format) fd_img.close() os.remove(in_file)
def ReFormat(ImageDir, Name): Filename = ImageDirectoryIn + ImageDir + '/' + Name with open(Filename, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_contain(image, [300, 300]) if not os.path.exists(ImageDirectoryOut + ImageDir + '/'): os.makedirs(ImageDirectoryOut + ImageDir + '/') cover.save(ImageDirectoryOut + ImageDir + '/' + Name, image.format)
def draw_image(self): print('Drawing new image') resized = resizeimage.resize_contain(self.original, self.screen_dim) self.image = ImageTk.PhotoImage(resized) self.display.delete("IMG") self.time_before = time.time() * 1000 self.display.create_image(0, 0, image=self.image, anchor=NW, tags="IMG")
def ReFormat(ImageDir, Name, Number): with open(ImageDir, 'r+b') as f: try: with Image.open(f) as image: cover = resizeimage.resize_contain(image, [300, 300]) cover.save(ImageDirectoryOut + Name + '_' + Number + '.jpg', image.format) except OSError: print("Error")
def Preprocess_Data(directory_path): i = 0 for img_path in glob.glob(directory_path + '/*.*'): with Image.open(img_path) as image: gray_resizedImage = resizeimage.resize_contain( image, [240, 160]).convert('L') # Source - Stackoverflow pixels = list(gray_resizedImage.getdata()) A[i] = pixels i += 1
def rescale(dir,dir_new,size): for img in os.listdir(dir): if img.endswith('.jpg'): with open(dir+img, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_contain(image, [size, size]) cover.save(dir_new+img, cover.format) print ('Finished')
def resizeImages(fileNames): fileNames.append('10000.png') #mage leah for fileName in fileNames: with open('%s%s' % (RAW_IMAGE_OUTPUT_LOCATION, fileName), 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_contain(image, [100, 100]) cover.save('%s%s' % (IMAGE_OUTPUT_LOCATION, fileName), image.format)
def read_and_save_image(image, filename, size=[256, 256]): img = Image.open(image, 'r') img = resizeimage.resize_contain(img, size) img = img.convert('RGB') if np.array(img).shape == (256, 256, 3): return ImageUpload.save_image(img, filename) else: return ''
def rescale(dir, dir_new, size): for img in os.listdir(dir): if img.endswith('.jpg'): with open(dir + img, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_contain(image, [size, size]) cover.save(dir_new + img, cover.format) print('Finished')
def test_size(url, photoB): distances = [] times = [] resizes = list(range(100, 10, -5)) for resize in range(100, 10, -5): resize *= 0.01 print resize start = time.time() stored_file = BytesIO(urllib2.urlopen(url).read()) with Image.open(stored_file) as image: width, height = image.size imageA = resizeimage.resize_contain( image, [int(resize * width), int(resize * height)]) imageA.save("imageA.png") with Image.open(photoB) as image: width, height = image.size imageB = resizeimage.resize_contain( image, [int(resize * width), int(resize * height)]) imageB.save("imageB.png") try: known_picture = face_recognition.load_image_file("imageA.png") known_face_encoding = face_recognition.face_encodings( known_picture)[0] unknown_picture = face_recognition.load_image_file("imageB.png") unknown_face_encoding = face_recognition.face_encodings( unknown_picture)[0] score = face_recognition.face_distance([known_face_encoding], unknown_face_encoding)[0] print 1 - score print(time.time() - start) distances.append(1 - score) times.append(time.time() - start) except: break print distances print times print resizes return (distances, times, resizes)
def test_resize_contain_larger_size(self): """ Test that the image resized with resize_contain has the expected size """ with self._open_test_image() as img: img = resizeimage.resize_contain(img, [801, 534]) filename = self._tmp_filename('resize-contain-larger.jpeg') img.save(filename, img.format) with Image.open(filename) as image: self.assertEqual(image.size, (801, 534))
def create_loop_thumbnail(self, loop_file): """ Creates a thumbnail for the specified video loop, which is already in self.path :param loop_file: Video file (inc extension), relative to self.path """ vlc_cmd = 'vlc \"' + os.path.join(self.path, loop_file) + '\" --rate=1 --scene-prefix=video_thumb --video-filter=scene --vout=dummy --aout=dummy --start-time=1 --stop-time=2 --scene-replace --scene-format=jpg --scene-path=\"' + self.thumb_path + '\" -V dummy --intf=dummy --dummy-quiet vlc://quit' ret_code = os.system(vlc_cmd) if ret_code == 0: with open(os.path.join(self.thumb_path, 'video_thumb.jpg'), 'r+b') as img_file: with Image.open(img_file) as image: sized_thumb = resizeimage.resize_contain(image, [88,50]) sized_thumb.save(os.path.join(self.thumb_path, os.path.splitext(loop_file)[0] + '.jpg'), image.format) return True
def generate(): for size, image_file in get_all_files().items(): try: os.remove(os.path.join(OUTPUT_DIR, image_file)) except FileNotFoundError: continue with open(ORIGINAL_IMAGE_PATH, 'rb') as original_image_file: with Image.open(original_image_file) as original_image: for size, image_name in get_all_files().items(): new_image = resizeimage.resize_contain(original_image, size) new_image.save(os.path.join(OUTPUT_DIR, image_name), original_image.format) favicon_image_details = [('icon', get_size_string(*size), filename) for size, filename in build_favicon_filenames().items()] apple_image_details = [('apple-touch-icon-precomposed', get_size_string(*size), filename) for size, filename in build_apple_filenames().items()] return favicon_image_details + apple_image_details
def test_resize_contain_bgcolor(self): """ Test that the image resized with resize_contain and a bgcolor has the correct background color in the background """ with self._open_test_image() as img: # testcolor evaluation only works when doing a (R,G,B)-type # color, not a hexstring, though its totally valid to send # a hexstring testcolor = (127, 128, 0) img = resizeimage.resize_contain(img, [200, 100], testcolor) filename = self._tmp_filename('resize-contain-bgcolor.jpeg') img.save(filename, img.format) with Image.open(filename) as image: image_rgb = image.convert('RGB') self.assertEqual(image_rgb.getpixel((1, 1)), testcolor)
def build_thumb(self, name): """ Deploys dynamic methods for on-demand thumbnails creation with any size. Syntax:: get_thumbnail_[WIDTH]x[HEIGHT]_[METHOD] Where *WIDTH* and *HEIGHT* are the pixels of the new thumbnail and *METHOD* can be ``url`` or ``filename``. Example usage:: >>> photo = Photo(photo="/tmp/example.jpg", ...) >>> photo.save() >>> photo.get_thumbnail_320x240_url() u"http://media.example.net/photos/2008/02/26/example_320x240.jpg" >>> photo.get_thumbnail_320x240_filename() u"/srv/media/photos/2008/02/26/example_320x240.jpg" """ match = re.match(GET_THUMB_PATTERN, name) if match is None: raise AttributeError, name width, height, method = match.groups() size = int(width), int(height) def get_image_thumbnail_filename(): file, ext = path.splitext(self.get_image_path()) return file + "_%sx%s" % size + ext def get_image_thumbnail_url(): url, ext = path.splitext(self.image_url) return url + "_%sx%s" % size + ext thumbnail = get_image_thumbnail_filename() if not path.exists(thumbnail): img = Image.open(self.get_image_path()) image = resizeimage.resize_contain(img, size) image.save(thumbnail) image.close() if method == "url": return get_image_thumbnail_url() else: return get_image_thumbnail_filename()
from PIL import Image from resizeimage import resizeimage import os ''' Resize all .jpg files in current directory to 400x300 pixels, new picture name will be: pic_{number}.jpg ''' i = 0 for filename in os.listdir("./"): if filename.endswith(".jpg"): i = i + 1 new_filename = "pic_"+str(i)+".jpg" try: # Try to resize the picture fd_img = open(filename, 'r') img = Image.open(fd_img) img = resizeimage.resize_contain(img, [400, 300]) img.save(new_filename, img.format) fd_img.close() print "Resized %s into %s" % (filename, new_filename) except: # Could not resize, just use the uploaded file instead print "Couldn't resize %s, renamed it to %s" % (filename, new_filename) os.rename(filename, new_filename) print "Processed %d files." % (i)