def get_image_resized(background, width, height): # Simple protection if width > 5000 or height > 5000: return "TOO BIG", 403 if width == 0 or height == 0: return "INVALID DIMENSIONS", 400 filename = os.path.basename(background) filename_without_extension, extension = os.path.splitext(filename) target = filename_without_extension + '-' + str(width) + 'x' + str( height) + extension dest_path = settings.backgrounds_folder + '/' + target if not os.path.exists(dest_path): resize_image(background, dest_path, format='jpg', quality=75, width=width, height=height, enlarge=True, mode='crop') return send_file(dest_path)
def generate_miniatures(path, user_id): user_id = str(user_id) for size in miniatures_sizes: dest_path = settings.avatars_folder + '/' + user_id + '-' + str( size) + '.png' resize_image(path, dest_path, format='png', width=size, height=size, enlarge=True)
def __call__(self, image_rois): # TODO: histogram equalization per channel # TODO: cv2 img = Image.open(image_rois[0]) img_path = os.path.join(self.features_path, os.path.basename(image_rois[0])) image.resize_image(img, (conf.image_size[0] // 2, conf.image_size[1] // 2))[0].save(img_path) feature_file_path = self.features_path + "/val.txt" with open(feature_file_path, "a+") as feature_file: feature_file.write(img_path[len(self.features_path):]) feature_file.write("\n")
def _down_file(photo,folder=None): try: url = photo.getURL(PHOTO_SIZE,'source') except: return 0 if folder == None: fpath = './data/photos/' else: fpath = './data/photos/%s/%s/' % (LICENSES[int(photo.license)],folder) if not os.path.exists(fpath): os.makedirs(fpath) fext = url.split('.')[-1] fname = '%s.%s' % (photo.title,fext) fsavename = '%s%s' % (fpath,fname) # 检查是否有缓存 cache_key = photo.id try: im = imagecache.get(cache_key) # 检查最终文件是否存在 exist_count = os.path.exists(fsavename) if (im != None and exist_count): return 3 if(im == None): if exist_count > 0: fname = '%s-%s.%s' % (photo.title,exist_count+1,fext) fsavename = '%s%s' % (fpath,fname) url_opener.retrieve(url,fsavename) im = Image.open(fsavename) imagecache.set(cache_key,im) if SIZE != None: new_size = SIZE else: new_size = im.size image.resize_image(im,fsavename,new_size,'flickr') except: return 2 return 1
def parse_test( root, dir_output, extensions, image_height=256, image_width=256, image_channels=3, resize_mode='squash', ): dir_output = os.path.expanduser( dir_output ) root = os.path.expanduser( root ) folder_out = os.path.join( dir_output, 'test' ) folder_in = os.path.join( root, 'test' ) images = make_dirs(folder_in, extensions) with open( os.path.join(dir_output, '{}.txt'.format( 'test' )) , 'w') as f: for i, path in enumerate( tqdm(images) ): #print(i, path) image_pathname = os.path.join(folder_out,'{:06d}.jpg'.format(i) ) # load image img = image.load_image(path) # transform img = image.resize_image(img, image_height, image_width, channels=image_channels, resize_mode=resize_mode, ) # save image PIL.Image.fromarray(img).save( image_pathname ) # save label f.write('{}\n'.format( image_pathname ) )
def resize_image(self, image): """ Resize an image using image_min_side and image_max_side. """ return resize_image(image, min_side=self.image_min_side, max_side=self.image_max_side) pass
def func_image (request, path) : __argument = request.GET.copy() __mode = __argument.get("mode", ) __direction = __argument.get("direction", "center") __update = __argument.has_key("update") try : __width = int(__argument.get("width", None)) except : __width = None else : __width = (__width > 0) and __width or None try : __height = int(__argument.get("height", None)) except : __height = None else : __height = (__height > 0) and __height or None if __width or __height : try : return image.resize_image( path, (__width, __height, ), mode=__mode, direction=__direction ) except Exception, e : print "[EE]" , e pass
def mold_inputs(self, images): """Takes a list of images and modifies them to the format expected as an input to the neural network. images: List of image matrices [height,width,depth]. Images can have different sizes. Returns 3 Numpy matrices: molded_images: [N, h, w, 3]. Images resized and normalized. image_metas: [N, length of meta data]. Details about each image. windows: [N, (y1, x1, y2, x2)]. The portion of the image that has the original image (padding excluded). """ molded_images = [] image_metas = [] windows = [] for image in images: # Resize image # TODO: move resizing to mold_image() original_shape = image.shape normalize(image, self.config.MEANS, self.config.STD) image, scale, window = resize_image(image, self.config.VIEW_SIZE) # Build image_meta image_meta = compose_image_meta( 0, original_shape, image.shape, window, scale, np.zeros([self.config.CLASSES], dtype=np.int32)) # Append molded_images.append(image) windows.append(window) image_metas.append(image_meta) # Pack into arrays molded_images = np.stack(molded_images) image_metas = np.stack(image_metas) windows = np.stack(windows) return molded_images, image_metas, windows
def resize_image(self, image, is_square_resize): """ Resize an image using image_min_side and image_max_side. """ if self.no_resize: return image, 1 else: return resize_image(image, min_side=self.image_min_side, max_side=self.image_max_side, is_square_resize=is_square_resize)
def func_image(request, cf): __argument = request.GET.copy() __mode = __argument.get( "mode", DEFAULT_IMAGE_RENDER_MODE, ) __direction = __argument.get("direction", "center") __update = __argument.has_key("update") try: __width = int(__argument.get("width", None)) except: __width = None else: __width = (__width > 0) and __width or None try: __height = int(__argument.get("height", None)) except: __height = None else: __height = (__height > 0) and __height or None if __width or __height: return image.resize_image( cf, ( __width, __height, ), mode=__mode, direction=__direction, improve=request.GET.has_key("improve"), ) try: return image.resize_image(cf, ( __width, __height, ), mode=__mode, direction=__direction) except Exception, e: print "[EE]", e
def save_image(data, filename): """Resize and upload image to S3 Bucket :param data: image data :param filename: string """ file_path = images.path(filename) if os.path.exists(file_path): os.remove(file_path) # Save temporary image and resize image_folder = 'static/images/activities/' bucket_name = os.environ.get('S3_BUCKET_NAME') images.save(data, None, filename) resize_image(filename) # Upload image to AWS S3 bucket file_path = image_folder + filename upload_file(file_path, bucket_name, filename)
def __call__(self, image_rois): # TODO: cv2 img = Image.open(image_rois[0]) label = np.zeros((img.size[1], img.size[0]), np.uint8) for roi in image_rois[1]: # class_id = conf.type2class_id[roi.r_type] # For the moment we only support binary segmentation class_id = 1 label[roi.tl_row:roi.br_row, roi.tl_col:roi.br_col] = class_id label_img = Image.fromarray(label, 'P') label_img.putpalette(conf.palette) label_path = self.labels_path + utils.to_png(image_rois[0]) image.resize_image(label_img, (conf.image_size[0] // 2, conf.image_size[1] // 2))[0].save(label_path) label_file_path = self.labels_path + "/val.txt" with open(label_file_path, "a+") as label_file: label_file.write(label_path[len(self.labels_path):]) label_file.write("\n")
def func_image (request, cf) : __argument = request.GET.copy() __mode = __argument.get("mode", DEFAULT_IMAGE_RENDER_MODE, ) __direction = __argument.get("direction", "center") __update = __argument.has_key("update") try : __width = int(__argument.get("width", None)) except : __width = None else : __width = (__width > 0) and __width or None try : __height = int(__argument.get("height", None)) except : __height = None else : __height = (__height > 0) and __height or None if __width or __height : return image.resize_image( cf, (__width, __height, ), mode=__mode, direction=__direction, improve=request.GET.has_key("improve"), ) try : return image.resize_image( cf, (__width, __height, ), mode=__mode, direction=__direction ) except Exception, e : print "[EE]" , e
def update(cls, obj, update_dict): image_stream = update_dict.get('id_image') for k, v in update_dict.iteritems(): if k in obj._meta.get_all_field_names() or (k == 'wechat_id'): setattr(obj, k, v) if image_stream: image_format = get_image_format(image_stream) file_name = '%s.%s' % (obj.user.username, image_format) image_stream.name = file_name obj.avatar = image_stream thumbnail = resize_image(image_stream, *settings.THUMBNAIL_SIZE) obj.thumbnail.save('thumbnail_%s' % file_name, File(thumbnail), save=False) obj.save()
def _load_image(self, index): imgId = self.annotations['imgIds'][index] bbox = self.annotations['bboxes'][index] label = self.annotations['labels'][index] image_info = self.coco.loadImgs(self.image_ids[imgId])[0] path = os.path.join(self.data_dir, 'images', image_info['file_name']) image = np.asarray(Image.open(path).convert('RGB')) image = image[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2]), ...] # resize image to target_size image, _ = resize_image(image, self.target_size) return image, label
def parse_train_and_validation( root, subfolder, dir_output, extensions, image_height=256, image_width=256, image_channels=3, resize_mode='squash', ): folder_in = os.path.join( root, subfolder ) folder_out = os.path.join( dir_output, subfolder ) classes, class_to_idx = find_classes( folder_in ) samples = make_dataset( folder_in, class_to_idx, extensions ) if len(samples) == 0: raise(RuntimeError("Found 0 files in subfolders of: " + folder_in + "\n" "Supported extensions are: " + ",".join(extensions))) with open( os.path.join(dir_output, '{}.txt'.format( 'labels' )) , 'w') as f: for c in classes: f.write('{}\n'.format( c )) pathname = os.path.join( dir_output, subfolder, c ) if os.path.exists(pathname) is not True: os.makedirs(pathname) with open( os.path.join(dir_output, '{}.txt'.format(subfolder)) , 'w') as f: for i, (path, tag) in enumerate( tqdm(samples) ): image_pathname = os.path.join(folder_out, classes[tag] ,'{:06d}.jpg'.format(i) ) # load image img = image.load_image(path) # transform img = image.resize_image(img, image_height, image_width, channels=image_channels, resize_mode=resize_mode, ) # save image PIL.Image.fromarray(img).save( image_pathname ) # save label f.write('{} {}\n'.format( image_pathname, tag) )
def detect(image, model, windows): bounding_boxes = [] ycrcb_image = rgb_to_ycrcb(image) scaled_hogs = {} scales = [1, 2] for scale in scales: scaled_hogs[scale] = hog_features_at_scale(ycrcb_image, scale) for ((start_x, start_y), (end_x, end_y), scale) in windows: slice_x = slice(start_x, end_x) slice_y = slice(start_y, end_y) image_slice = ycrcb_image[slice_y, slice_x] image_slice = resize_image(image_slice) hog_slices = hog_features_for_slice_at_scale(scaled_hogs, scale, (start_x, start_y), (end_x, end_y)) hog_channel_1_slice, hog_channel_2_slice, hog_channel_3_slice = hog_slices # hog_channel_1_slice = np.array(hog_features_for_channel(image_slice, 0, feature_vector=False)) # hog_channel_2_slice = np.array(hog_features_for_channel(image_slice, 1, feature_vector=False)) # hog_channel_3_slice = np.array(hog_features_for_channel(image_slice, 2, feature_vector=False)) hog_features = combine_hog_features(np.ravel(hog_channel_1_slice), np.ravel(hog_channel_2_slice), np.ravel(hog_channel_3_slice), feature_vector=True) features = combine_features(hog_features, color_histogram_features(image_slice), spatial_binning_features(image_slice)) prediction = model.predict(features) if prediction == 1: bounding_boxes.append(((start_x, start_y), (end_x, end_y))) return bounding_boxes
def preprocess_img(img_path): image = np.asarray(Image.open(img_path).convert('RGB')) image = image[:, :, ::-1].copy() # visual_effect_generator = random_visual_effect_generator( # contrast_range=(0.9, 1.1), # brightness_range=(-.1, .1), # hue_range=(-0.05, 0.05), # saturation_range=(0.95, 1.05) # ) # # visual_effect = next(visual_effect_generator) # # apply visual effect # image = visual_effect(image_bgr) image = image.astype(np.float32) image -= [103.939, 116.779, 123.68] # resize image image, image_scale = resize_image(image) return image, image_scale pass
def spatial_binning_features(image, size=(32, 32)): """Gathers all the image pixel information into a 1-D array""" return resize_image(image, size).ravel()
def thumbnail(filename): orig_filename = os.path.join(app.config['IMAGES_ORIGINAL_DIR'], filename) img_filename = os.path.join(app.config['IMAGES_THUMBNAIL_DIR'], filename) resize_image(orig_filename, img_filename, app.config['IMAGES_THUMBNAIL_SIZE']) return send_file(img_filename)
def main(): args = parse() print( transform_to_ascii( args.gray(resize_image(get_image(args.image), args.width))))