def _save_images_to_local_disk(self, user, image, storage_dir): user_id = str(user.id) original_filename = "%s-%s.jpg" % (user_id, 'web') original_file_path = '%s/%s' % (storage_dir, original_filename) thumbnail_filename = '%s-%s.jpg' % (user_id, 'thumbnail') thumbnail_file_path = '%s/%s' % (storage_dir, thumbnail_filename) msg = "Saving user profile image to: %s" % original_file_path current_app.logger.info(msg) f = open(original_file_path, 'wb') f.write(base64.b64decode(image)) f.close() im = Image.open(original_file_path); thumbnail_image = cropresize.crop_resize(im, (71, 96)); msg = "Saving user profile image thumbnail to: %s" % thumbnail_file_path current_app.logger.info(msg) thumbnail_image.save(thumbnail_file_path, 'JPEG', quality=100) return { "original_filename": original_filename, "original_file_path": original_file_path, "thumbnail_filename": thumbnail_filename, "thumbnail_file_path": thumbnail_file_path, }
def get_img2gist(): try: img2gist = None with open(name2gist_file, 'rb') as f: print 'loading existed img2gist...' sys.stdout.flush() img2gist = pickle.load(f) return img2gist except Exception: img2gist = {} total_num = 0 with open(train_file_map, 'r') as f: for line in f: if line.strip(): total_num += 1 count = 0 with open(train_file_map, 'r') as f: for line in f: if line.strip(): count += 1 arr = line.strip().split() name = arr[0].strip() rpath = arr[1].strip() im = Image.open(pjoin(train_images_dir, rpath)) im = crop_resize(im, normal_size, True) desc = leargist.color_gist(im) img2gist[name] = desc sys.stdout.write( '%d/%d\r size:(%d, %d) ' % (count, total_num, im.size[0], im.size[1])) sys.stdout.flush() with open(name2gist_file, 'wb') as f: pickle.dump(img2gist, f) return img2gist
def rsize(cls, oldPaste, weight, height): assert oldPaste.is_image img = cropresize.crop_resize(Image.open(oldPaste.path), (int(weight), int(height))) return cls.create_by_img(img, oldPaste.filename, oldPaste.mimetype)
def _save_images_to_local_disk(self, user, image, storage_dir): user_id = str(user.id) original_filename = "%s-%s.jpg" % (user_id, 'web') original_file_path = '%s/%s' % (storage_dir, original_filename) thumbnail_filename = '%s-%s.jpg' % (user_id, 'thumbnail') thumbnail_file_path = '%s/%s' % (storage_dir, thumbnail_filename) squareimg_filename = '%s-%s.jpg' % (user_id, 'square') squareimg_file_path = '%s/%s' % (storage_dir, squareimg_filename) msg = "Saving user profile image to: %s" % original_file_path current_app.logger.info(msg) f = open(original_file_path, 'wb') # We may receive a FileStorage type: if isinstance(image, FileStorage): if hasattr(image.stream, 'getvalue'): image = image.stream.getvalue() else: image = image.stream.read() f.write(image) else: f.write(base64.b64decode(image)) f.close() im = Image.open(original_file_path); thumbnail_image = cropresize.crop_resize(im, (71, 96)); square_image = cropresize.crop_resize(im, (71, 71)); msg = "Saving user profile image thumbnail to: %s" % thumbnail_file_path current_app.logger.info(msg) thumbnail_image.save(thumbnail_file_path, 'JPEG', quality=100) square_image.save(squareimg_file_path, 'JPEG', quality=100) return { "original_filename": original_filename, "original_file_path": original_file_path, "thumbnail_filename": thumbnail_filename, "thumbnail_file_path": thumbnail_file_path, "squareimg_filename": squareimg_filename, "squareimg_file_path": squareimg_file_path, }
def create_file_after_crop(cls, uploadedFile, width, height): assert uploadedFile.is_image, TypeError("Unsupported Image Type.") img = cropresize.crop_resize(Image.open(uploadedFile), (int(width), int(height))) rst = cls(uploadedFile.filename, uploadedFile.mimetype, 0) img.save(rst.path) filestat = os.stat(rst.path) rst.size = filestat.st_size return rst
def main_proc(query, image_path, random=False, query_cache=False, image_cache=False): """ Return distance of a (query, image) pair """ if random: return np.random.rand() global img2gist, query_miss, hash_miss, query_top10_cache, image_top10_cache if img2gist is None: img2gist = get_img2gist() im = Image.open(image_path) im = crop_resize(im, normal_size, True) desc = leargist.color_gist(im) if query_cache: A = query_top10_cache else: t1 = -time.time() A = query_top10_images(query) query_top10_cache = A print 'time for query_top10_images:', time.time() + t1 if image_cache: B = image_top10_cache else: t2 = -time.time() B = gist_top10_images(image_path) image_top10_cache = B print 'time for gist_top10_images:', time.time() + t2 if not A: if not query_cache: query_miss += 1 return np.random.rand() if not B: hash_miss += 1 sim_set = [] t3 = -time.time() for i in A: gist_i = img2gist[i] for j in B: v = np.sum((gist_i - img2gist[j])**2) sim_set.append(v) sim_set.append(np.sum((gist_i - desc)**2)) print 'time for compare:', time.time() + t3 return min(sim_set)
def create_file_after_crop(cls, uploadedFile, width, height): assert uploadedFile.is_image, TypeError("Unsupported Image Type.") img = cropresize.crop_resize(Image.open(uploadedFile), (int(width), int(height))) rst = cls(uploadedFile.filename, uploadedFile.mimetype, 0) img.save(rst.path) filestat = os.stat(rst.path) rst.size = filestat.st_size return rst
def main_proc(query, image_path, random=False, query_cache=False, image_cache=False): """ Return distance of a (query, image) pair """ if random: return np.random.rand() global img2gist, query_miss, hash_miss, query_top10_cache, image_top10_cache if img2gist is None: img2gist = get_img2gist() im = Image.open(image_path) im = crop_resize(im, normal_size, True) desc = leargist.color_gist(im) if query_cache: A = query_top10_cache else: t1 = -time.time() A = query_top10_images(query) query_top10_cache = A print 'time for query_top10_images:', time.time() + t1 if image_cache: B = image_top10_cache else: t2 = -time.time() B = gist_top10_images(image_path) image_top10_cache = B print 'time for gist_top10_images:', time.time() + t2 if not A: if not query_cache: query_miss += 1 return np.random.rand() if not B: hash_miss += 1 sim_set = [] t3 = -time.time() for i in A: gist_i = img2gist[i] for j in B: v = np.sum((gist_i - img2gist[j]) ** 2) sim_set.append(v) sim_set.append(np.sum((gist_i - desc) ** 2)) print 'time for compare:', time.time() + t3 return min(sim_set)
def create_sizes(self, ticket, attachment): """create the sizes for a ticket image""" filename = attachment.filename # add the specified sizes as attachments sizes = self.sizes() for name, size in sizes.items(): # crop the image image = Image.open(attachment.path) i = crop_resize(image, size) buffer = StringIO() i.save(buffer, image.format) buffer.seek(0,2) # seek to end of file filesize = buffer.tell() buffer.seek(0) a = Attachment(self.env, 'ticket', ticket.id) a.author = ticket['reporter'] a.description = ticket['summary'] f = ('.%sx%s.' % (size[0] or '', size[1] or '')).join(filename.rsplit('.', 1)) # XXX assumes the file has an extension a.insert(f, buffer, filesize)
def create_sizes(self, ticket, attachment): """create the sizes for a ticket image""" filename = attachment.filename # add the specified sizes as attachments sizes = self.sizes() for name, size in sizes.items(): # crop the image image = Image.open(attachment.path) i = crop_resize(image, size) buffer = StringIO() i.save(buffer, image.format) buffer.seek(0, 2) # seek to end of file filesize = buffer.tell() buffer.seek(0) a = Attachment(self.env, 'ticket', ticket.id) a.author = ticket['reporter'] a.description = ticket['summary'] f = ('.%sx%s.' % (size[0] or '', size[1] or '')).join( filename.rsplit('.', 1)) # XXX assumes the file has an extension a.insert(f, buffer, filesize)
def gist_top10_images(img): """ 32 bit hash: bucket ratio: 225410/4294967296 max conflicts: 8691 16 bit hash: bucket ratio: 8135/65536 max conficts: 93329 """ global lsh # name2path = get_name2path(train_file_map) # info of known dataset # print lsh.hash_tables[0].keys()[0] # print 'bucket ratio: %d/%d' % (len(lsh.hash_tables[0].keys()), 2 ** hash_len) # counts = [] # t = lsh.hash_tables[0] # for k in t.keys(): # counts.append(len(t.get_list(k))) # print 'max conflicts:', max(counts) # print 'min conflicts:', min(counts) im = Image.open(img) im = crop_resize(im, normal_size, True) desc = leargist.color_gist(im) # for i in xrange(len(desc)): # desc[i] += 0.01 res = lsh.query(desc, num_results=10, distance_func="euclidean") # print 'num of results:', len(res) # for i in res: # name = json.loads(i[0])[1] # print name, name2path[name], i[1] return [json.loads(i[0])[1] for i in res]
def __call__(self, request, data): # add width + height data data['width'] = self.width data['height'] = self.height # filter out non-images _files = [] for f in data['files']: mimetype = mimetypes.guess_type(f['name'])[0] if mimetype and mimetype.split('/')[0] == 'image': _files.append(f) f['link'] = f['path'] data['files'] = _files # columns for grid display if self.columns is None: data['columns'] = len(data['files']) else: data['columns'] = int(self.columns) # thumbnails if 'thumbnails' not in self.args: return thumb_dir = self.thumb_dir if not os.path.isabs(thumb_dir): thumb_dir = os.path.join(data['directory'], self.thumb_dir) else: raise NotImplementedError if not os.path.exists(thumb_dir): os.mkdir(thumb_dir) for f in data['files']: filepath = os.path.join(data['directory'], f['name']) thumbnail = '%s%s' % (self.thumb_prefix, f['name']) thumbnail_file = os.path.join(data['directory'], thumb_dir, thumbnail) create_thumbnail = False if os.path.exists(thumbnail_file): try: # ensure the size is smaller than the specified size thumb = Image.open(thumbnail_file) if self.width and thumb.size[0] > self.width: create_thumbnail = True if self.height and thumb.size[1] > self.height: create_thumbnail = True except: pass # ensure the original file has not been modified if os.path.getmtime(thumbnail_file) < os.path.getmtime( filepath): create_thumbnail = True else: # create a new thumbnail create_thumbnail = True if create_thumbnail: # do thumbnail creation flag = False try: image = Image.open(filepath) thumbnail_image = crop_resize(image, (self.width, self.height)) fd = file(thumbnail_file, 'w') flag = True thumbnail_image.save(fd) fd.close() except Exception, e: # failure to create thumbnail # cleanup file if flag: fd.close() os.remove(thumbnail_file) # fix the path to point to the thumbnail if os.path.exists(thumbnail_file): f['path'] = '%s/%s/%s' % (f['path'].rsplit( '/', 1)[0], self.thumb_dir, thumbnail)
#/usr/bin/env python import Image import cropresize import os files = os.listdir('images/') files = [f for f in files if not str(f) == '.DS_Store'] for f in files: img = Image.open('images/' + str(f)) img = cropresize.crop_resize(img, (230, 172)) img.save('thumbs/' + str(f)) print """<a class="fancybox" href="images/may2013/images/{0}" rel="may2013"><img src="images/may2013/thumbs/{0}"></a> """.format(str(f))
def rsize(cls, oldPaste, weight, height): assert oldPaste.is_image img = cropresize.crop_resize(Image.open(oldPaste.path), (int(weight), int(height))) return cls.create_by_img(img, oldPaste.filename, oldPaste.mimetype)
def _resize(self, im, size, upscale): return crop_resize(im, size, exact_size=upscale)