def generate_thumbnail(file_path, size, bounds=None, force=False, img=None): """ Fits image to the given size in order to generate its thumbnail. Keyword arguments: file_path -- absolute path of file size -- int tuple, for example (200, 200) """ (thumbnail_path, file_extension) = splitext(file_path) thumbnail_path = '%s-%sx%s%s' % (thumbnail_path, size[0], size[1], file_extension) if not exists(thumbnail_path) or force: # allow truncated images ImageFile.LOAD_TRUNCATED_IMAGES = True if img is None: img = Image.open(file_path) if bounds: img = img.crop(bounds) if size[0] and size[1]: thumbnail = fit(img, size, Image.ANTIALIAS) thumbnail.save(thumbnail_path) else: x, y = size if not size[0]: x = img.size[0] if not size[1]: y = img.size[1] size = (x, y) img.thumbnail(size, Image.ANTIALIAS) img.save(thumbnail_path)
def create_image(top_text: str, bottom_text: str, icon: Image): image_size = get_size_of_image(top_text, bottom_text) # Image image = Image.new('RGBA', (image_size['x'], image_size['y']), color=(0, 0, 0, 0)) imagedraw = ImageDraw.Draw(image) # Background black_bg_cords = [[6, 0], [0, 6], [4, 2], [2, 4]] draw_rectangles(imagedraw, image_size, black_bg_cords, 'black') light_gray_bg_cords = [[6, 2], [2, 6], [4, 4]] draw_rectangles(imagedraw, image_size, light_gray_bg_cords, (85, 85, 85)) dark_gray_bg_cords = [[8, 6], [6, 8]] draw_rectangles(imagedraw, image_size, dark_gray_bg_cords, (33, 33, 33)) # Text font = get_font(16) imagedraw.text((60, 14), top_text, font=font, fill=(255, 255, 0)) imagedraw.text((60, 36), bottom_text, font=font, fill=(255, 255, 255)) # Icon icon = fit(icon, (icon_size, icon_size), Image.ANTIALIAS) try: image.paste(icon, (15, 16), mask=icon) except ValueError: image.paste(icon, (15, 16)) return image
def _save_scaled_cropped_img(src, dest): image = load_img(src) # Returns a sized and cropped version of the image, # cropped to the requested aspect ratio and size. image = fit(image, IMGS_DIM_2D, method=LANCZOS) image.save(dest) return image
def post_image(file): image = Image.open(io.BytesIO(file.read())) image = fit(image, (50, 50)) image_bytes = image.tobytes() image_array = np.reshape(np.frombuffer(image_bytes, dtype=np.uint8), (1, 50, 50, 3)) prediction = DOGSVSCATS_MODEL.predict(image_array) print(prediction[0][0]) return json.dumps({'animal': animal_array[int(prediction[0][0])]})
def make_test_data(): print('changing data...') data_img = [] img = imread(opts.eval_root) img = Image.fromarray(img) img = fit(img, size=(64, 64)) img = transpose(img, (2, 0, 1)) data_img.append(img) np.save('./test_data/test.npy', np.asarray(data_img))
def gen_image_thumbnails(media): s3conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) bucket = s3conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME) orig = Image.open(BytesIO(requests.get(media.file).content)) # create the small 50x50 icon tmp = BytesIO() thumb = fit(orig, (50, 50), method=Image.BICUBIC) thumb.save(tmp, format='jpeg') tmp.seek(0) k = Key(bucket) k.key = 'media_thumbs/{}_{}.jpg'.format(media.filename(), 's') k.set_contents_from_file(tmp) k.make_public() tmp.close() # create the medium sized thumbnail tmp = BytesIO() thumb = fit(orig, (320, 214), method=Image.BICUBIC) thumb.save(tmp, format='jpeg') tmp.seek(0) k = Key(bucket) k.key = 'media_thumbs/{}_{}.jpg'.format(media.filename(), 'm') k.set_contents_from_file(tmp) k.make_public() tmp.close() # create the large sized thumbnail tmp = BytesIO() im = orig.copy() im.thumbnail((1000, 1000)) im.save(tmp, format='jpeg') tmp.seek(0) k = Key(bucket) k.key = 'media_thumbs/{}_{}.jpg'.format(media.filename(), 'l') k.set_contents_from_file(tmp) k.make_public() tmp.close()
def _save_preprocessed_img(imgs_dim, src, dest): try: image = load_img(src) except FileNotFoundError: print("Image {:s} not found and skipped".format(src)) return # todo: preprocess image = fit(image, (imgs_dim, imgs_dim), method=LANCZOS) image.save(dest)
def get_cropped_image(theme, x, y, grey = None): '''crops a random image from a given theme.''' im_list = os.listdir('./images/%s' % theme) im_src = im_list[ randint(1,len(im_list)) - 1 ] im = Image.open("images/%s/%s" % (theme, im_src)) out = im max_x, max_y = im.size if x < max_x or y < max_y: out = fit(im, (x, y), Image.ANTIALIAS, 0, (.5, .5)) if grey != None: out = grayscale(out) return out
def multi_setup_pillow(monitors, save_path): images = list(map(Image.open, [m.wallpaper for m in monitors])) resolutions = [(m.width, m.height) for m in monitors] widths = [r[0] for r in resolutions] heights = [r[1] for r in resolutions] offsets = [(m.offset_x, m.offset_y) for m in monitors] n_images = [] for i, r in zip(images, resolutions): n_images.append(fit(i, r, method=Image.LANCZOS)) final_image = Image.new('RGB', (sum(widths), max(heights))) for i, o in zip(n_images, offsets): final_image.paste(i, o) final_image.save(save_path)
def download_img(meme_data): url, name = meme_data try: with requests.get(url) as response: raw_img = Image.open(io.BytesIO(response.content)) except: pass else: img = fit(raw_img, (224, 224), Image.ANTIALIAS) img = raw_img.convert('RGB') img_hash = hashlib.md5(img.tobytes()).hexdigest() output_filename = os.path.join(DATASET_PATH, f"{name}", f"{img_hash}.png") with open(output_filename, 'wb') as out_file: img.save(out_file, format='png')
def post_image(file): """ Given a posted image, classify it using the pretrained model. This will take 'any size' image, and scale it down to 28x28 like our MNIST training data -- and convert to grayscale. Parameters ---------- file: Bytestring contents of the uploaded file. This will be in an image file format. """ image = Image.open(io.BytesIO(file.read())) image = grayscale(fit(image, (28, 28))) image_bytes = image.tobytes() image_array = np.reshape(np.frombuffer(image_bytes, dtype=np.uint8), (28, 28)) print(image_array.shape) return json.dumps({'digit': None})
def multi_setup_pillow(monitors, save_path, wp_setter_func=None): images = list(map(Image.open, [m.wallpaper for m in monitors])) resolutions = [(m.width * m.scaling, m.height * m.scaling) for m in monitors] offsets = [(m.offset_x, m.offset_y) for m in monitors] # DEBUG # for m in monitors: # print(m) final_image_width = max([m.offset_x + m.width * m.scaling for m in monitors]) final_image_height = max([m.offset_y + m.height * m.scaling for m in monitors]) # DEBUG # print('Final Size: {} x {}'.format(final_image_width, final_image_height)) n_images = [] for i, r in zip(images, resolutions): n_images.append(fit(i, r, method=Image.LANCZOS)) final_image = Image.new('RGB', (final_image_width, final_image_height)) for i, o in zip(n_images, offsets): final_image.paste(i, o) final_image.save(save_path)
def post_image(file): """ Given a posted image, classify it using the pretrained model. This will take 'any size' image, and scale it down to 28x28 like our MNIST training data -- and convert to grayscale. Parameters ---------- file: Bytestring contents of the uploaded file. This will be in an image file format. """ #using Pillow -- python image processing -- to turn the poseted file into bytes image = Image.open(io.BytesIO(file.read())) image = grayscale(fit(image, (28, 28))) image_bytes = image.tobytes() #image needs to be a 'batch' though only of one, and with one channel -- grayscale image_array = np.reshape(np.frombuffer(image_bytes, dtype=np.uint8), (1, 28, 28, 1)) prediction = MNIST_MODEL.predict(image_array) #argmax to reverse the one hot encoding digit = np.argmax(prediction[0]) #need to convert to int -- numpy.int64 isn't known to serialize return json.dumps({'digit': int(digit)})
def save(self, **kwargs): super(Profile, self).save() if self.image: image = Image.open(storage.open(self.image.name)) try: for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation]=='Orientation': break exif=dict(image._getexif().items()) if exif[orientation] == 3: image=image.rotate(180, expand=True) elif exif[orientation] == 6: image=image.rotate(270, expand=True) elif exif[orientation] == 8: image=image.rotate(90, expand=True) except (AttributeError, KeyError, IndexError): # cases: image don't have getexif pass image = fit(image, (200, 200), Image.ANTIALIAS) fh = storage.open(self.image.name, "wb") format = 'png' # You need to set the correct image format here image.save(fh, format) fh.close()
def _save_scaled_cropped_img(src, dest): image = load_img(src) image = fit(image, IMGS_DIM_2D, method=LANCZOS) image.save(dest) return image
def printcoords(): File = filedialog.askopenfilename(parent=root, title='Choose an image.') print('changing data...') data_img = [] img = imread(File) img = Image.fromarray(img) img = fit(img, size=(64, 64)) img = transpose(img, (2, 0, 1)) data_img.append(img) np.save(opts.path, np.asarray(data_img)) test_dataset = TestData(label=opts.label, path=opts.path, transform=transforms.ToTensor()) dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=1) cvae = CVAE(200).to(device) cvae.load_params(opts.CVAE_PATH) evaluation_dir = opts.CVAE_PATH + 'evalFolder' try: os.mkdir(evaluation_dir) except: print('file already created') cvae.eval() test_x, test_y = iter(dataloader).next() for i in range(3): test_rec, test_mean, test_log_var, test_predict = cvae(test_x, test_y) save_image(test_x.data, join(evaluation_dir, 'input.png')) save_image(test_rec.data, join(evaluation_dir, 'output_test.png')) x = test_x.data y = test_y mu, logVar, y = cvae.encode(x) z = cvae.reparameterization(mu, logVar) sample1 = cvae.decode( torch.LongTensor(np.ones(y.size(), dtype=int)).type_as(z), z) sample2 = cvae.decode( torch.LongTensor(np.zeros(y.size(), dtype=int)).type_as(z), z) save_image(sample1.cpu().data, join(evaluation_dir, 'sample1.png')) save_image(sample2.cpu().data, join(evaluation_dir, 'sample2.png')) arr = ['input.png', 'sample1.png', 'sample2.png'] toImage = Image.new('RGBA', (584, 128)) for j in range(3): fromImge = Image.open(join(evaluation_dir, arr[j])) fromImge = fromImge.resize((128, 128), Image.ANTIALIAS) loc = (128 * j + 80, 0) toImage.paste(fromImge, loc) toImage.save('merged' + str(i) + '.png') arr = ['merged0.png', 'merged1.png', 'merged2.png'] toImage = Image.new('RGBA', (584, 384)) for j in range(3): fromImge = Image.open(arr[j]) loc = (0, 128 * j) toImage.paste(fromImge, loc) toImage.save('merged.png') filename = ImageTk.PhotoImage(Image.open('merged.png')) canvas.image = filename canvas.create_image(124, 10, anchor='nw', image=filename)
inDirAtt ='/Users/edoardocalvello/Documents/Representation_Learning_2020/celebA/list_attr_celeba.txt' inDirIm='/Users/edoardocalvello/Documents/Representation_Learning_2020/celebA/img_align_celeba' IMSIZE=64 f = open(inDirAtt) noSamples = int(f.readline()) print('There are %d samples' % noSamples) labels = f.readline().split(' ') print(labels, type(labels)) dataX = [] dataY = [] for i, line in enumerate(f): imName, labels = line.split(' ')[0], line.split(' ')[1:] label = np.loadtxt(labels) print(imName, label) print(i) im = imread(join(inDirIm, imName)) im = Image.fromarray(im) im = fit(im, size=(IMSIZE, IMSIZE)) label = label.astype('int') im = np.transpose(im, (2, 0, 1)) dataX.append(im) dataY.append(label) print(np.shape(dataX)) print(np.shape(dataY)) np.save('/Users/edoardocalvello/Documents/Representation_Learning_2020/xTrain.npy', np.asarray(dataX)) np.save('/Users/edoardocalvello/Documents/Representation_Learning_2020/yAllTrain.npy', np.asarray(dataY))
def make_data(): print('making data...') img_path = opts.root + 'img_align_celeba/' attr_path = opts.root + 'list_attr_celeba.txt' f = open(attr_path) f.readline() labels_name = f.readline().split(' ') data_img = [] data_label = [] attr_index = attributes.index(opts.attr) count_true = 0 count_false = 0 for index, line in enumerate(f): print(line) line_array = line.split(' ') img_name = line_array[0] labels = line_array[1:] img = imread(img_path + img_name) print(np.shape(img)) img = Image.fromarray(img) img = fit(img, size=(64, 64)) # (64, 64, 3) label = loadtxt(labels).astype('int') img = transpose(img, (2, 0, 1)) # (3, 64, 64) data_img.append(img) data_label.append(label) if label[attr_index] == 1: count_true += 1 else: count_false += 1 if opts.test_mode and index is 100: break print(np.shape(data_img)) print(np.shape(data_label)) if not opts.test_mode: print('true: ' + str(count_true)) print('false: ' + str(count_false)) np.save('./celebA/img.npy', np.asarray(data_img)) np.save('./celebA/attr.npy', np.asarray(data_label)) else: print('test_mode') true_label = 0 false_label = 0 while true_label is 0 or false_label is 0: # print(true_label) # print(false_label) index = random.randint(0,100) label = data_label[index][attr_index] if label == 1 and true_label == 0: plt.figure() plt.title('true') true_label = 1 plt.imshow(data_img[index].transpose(1,2,0)) elif label == -1 and false_label == 0: plt.figure() plt.title('false') false_label = 1 plt.imshow(data_img[index].transpose(1,2,0)) # data_label = np.asarray(data_label) # data_img = np.asarray(data_img) plt.show()