我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用keras.preprocessing.image.array_to_img()。
def main(): model = train_autoencoder.build_model() model = tflearn.DNN(model) logging.info('loading checkpoint') checkpoint_path = sys.argv[1] model.load(checkpoint_path) img_path = sys.argv[2] img_arr = get_img(img_path) logging.info('getting output') pred = model.predict(img_arr) logging.debug('saving output to output.jpg') pred = pred[0] pred_img = image.array_to_img(pred) pred_img.save('output.jpg')
def resize(item, target_h, target_w, keep_aspect_ratio=False): """ Resizes an image to match target dimensions :type item: np.ndarray :type target_h: int :type target_w: int :param item: 3d numpy array or PIL.Image :param target_h: height in pixels :param target_w: width in pixels :param keep_aspect_ratio: If False then image is rescaled to smallest dimension and then cropped :return: 3d numpy array """ img = array_to_img(item, scale=False) if keep_aspect_ratio: img.thumbnail((target_w, target_w), PILImage.ANTIALIAS) img_resized = img else: img_resized = img.resize((target_w, target_h), resample=PILImage.NEAREST) # convert output img_resized = img_to_array(img_resized) img_resized = img_resized.astype(dtype=np.uint8) return img_resized
def extract_vgg16_features(x): from keras.preprocessing.image import img_to_array, array_to_img from keras.applications.vgg16 import preprocess_input, VGG16 from keras.models import Model # im_h = x.shape[1] im_h = 224 model = VGG16(include_top=True, weights='imagenet', input_shape=(im_h, im_h, 3)) # if flatten: # add_layer = Flatten() # else: # add_layer = GlobalMaxPool2D() # feature_model = Model(model.input, add_layer(model.output)) feature_model = Model(model.input, model.get_layer('fc1').output) print('extracting features...') x = np.asarray([img_to_array(array_to_img(im, scale=False).resize((im_h,im_h))) for im in x]) x = preprocess_input(x) # data - 127. #data/255.# features = feature_model.predict(x) print('Features shape = ', features.shape) return features
def test_pair_crop(crop_function): arr1 = np.random.random(500, 800) arr2 = np.random.random(500, 800) img1 = PILImage.fromarray(arr1) img2 = PILImage.fromarray(arr2) crop_width = img1.width / 5 crop_height = img1.height / 5 result1, result2 = crop_function(img_to_array(img1), img_to_array(img2), (crop_height, crop_width), 'channels_last') result1 = array_to_img(result1) result2 = array_to_img(result2) assert result1.width == crop_width == result2.width assert result2.height == crop_height == result2.height
def run(segmenter, data): data_gen = data['data_gen'] num_instances = data['num_instances'] out_directory = os.path.realpath(data['dir_target']) keep_context = data['keep_context'] # dataset = getattr(datasets, data['dataset_name'])(**data) dataset = getattr(datasets, data['dataset_name']) for idx, image in enumerate(data_gen): if idx > 20: break print('Processing {} out of {}'.format(idx+1, num_instances), end='\r') pred_final, scores = predict(segmenter, image, h=dh, w=dw) # draw prediction as rgb pred_final = color_output_image(dataset.palette, pred_final[:, :, 0]) pred_final = array_to_img(pred_final) out_file = os.path.join( out_directory, '{}_{}_{}_out.png'.format( idx, keep_context, utils.basename_without_ext(pw))) sys.stdout.flush() if os.path.isfile(out_file): continue utils.ensure_dir(out_directory) print('Saving output to {}'.format(out_file)) pilimg = PILImage.fromarray(image.astype(np.uint8), mode='RGB') pilimg.save(out_file.replace('_out.png', '.png')) pred_final.save(out_file)
def make_image(self, data): from keras.preprocessing.image import array_to_img try: if len(data.shape) == 2: # grayscale image, just add once channel data = data.reshape((data.shape[0], data.shape[1], 1)) image = array_to_img(data) except Exception: return None # image = image.resize((128, 128)) return image
def make_image_from_dense_softmax(self, neurons): from aetros.utils import array_to_img img = array_to_img(neurons.reshape((1, len(neurons), 1))) img = img.resize((9, len(neurons) * 8)) return img
def make_image_from_dense(self, neurons): from aetros.utils import array_to_img cols = int(math.ceil(math.sqrt(len(neurons)))) even_length = cols * cols diff = even_length - len(neurons) if diff > 0: neurons = np.append(neurons, np.zeros(diff, dtype=neurons.dtype)) img = array_to_img(neurons.reshape((1, cols, cols))) img = img.resize((cols * 8, cols * 8)) return img
def test_img_utils(self): height, width = 10, 8 # Test th dim ordering x = np.random.random((3, height, width)) img = image.array_to_img(x, dim_ordering='th') assert img.size == (width, height) x = image.img_to_array(img, dim_ordering='th') assert x.shape == (3, height, width) # Test 2D x = np.random.random((1, height, width)) img = image.array_to_img(x, dim_ordering='th') assert img.size == (width, height) x = image.img_to_array(img, dim_ordering='th') assert x.shape == (1, height, width) # Test tf dim ordering x = np.random.random((height, width, 3)) img = image.array_to_img(x, dim_ordering='tf') assert img.size == (width, height) x = image.img_to_array(img, dim_ordering='tf') assert x.shape == (height, width, 3) # Test 2D x = np.random.random((height, width, 1)) img = image.array_to_img(x, dim_ordering='tf') assert img.size == (width, height) x = image.img_to_array(img, dim_ordering='tf') assert x.shape == (height, width, 1)
def save_image(image_array, image_file): image = array_to_img(image_array) image.save(image_file)
def test_crop(crop_function): arr = np.random.random(500, 800) img = PILImage.fromarray(arr) crop_width = img.width / 5 crop_height = img.height / 5 result = crop_function(img_to_array(img), (crop_height, crop_width), 'channels_last') result = array_to_img(result) assert result.width == crop_width assert result.height == crop_height
def Augmentation(self): # ??3???train?label, ???????, ???label????????train??2???, ????? print("?? Augmentation") """ Start augmentation..... """ trains = self.train_imgs labels = self.label_imgs path_train = self.train_path path_label = self.label_path path_merge = self.merge_path imgtype = self.img_type path_aug_merge = self.aug_merge_path print(len(trains), len(labels)) if len(trains) != len(labels) or len(trains) == 0 or len(trains) == 0: print("trains can't match labels") return 0 for i in range(len(trains)): img_t = load_img(path_train + "/" + str(i) + "." + imgtype) # ??train img_l = load_img(path_label + "/" + str(i) + "." + imgtype) # ??label x_t = img_to_array(img_t) # ????? x_l = img_to_array(img_l) x_t[:, :, 2] = x_l[:, :, 0] # ?label??train?????? img_tmp = array_to_img(x_t) img_tmp.save(path_merge + "/" + str(i) + "." + imgtype) # ???????? img = x_t img = img.reshape((1,) + img.shape) # ??shape(1, 512, 512, 3) savedir = path_aug_merge + "/" + str(i) # ?????????? if not os.path.lexists(savedir): os.mkdir(savedir) self.doAugmentate(img, savedir, str(i)) # ????
def extract_coco_labels(target_dir): kwargs = { 'h': 512, 'w': 512, 'batch_size': 2, 'root_dir': 'data', 'dataset_name': 'mscoco', 'data_type': 'train2017', 'sample_size': 0.01, 'instance_mode': False, 'keep_context': 0.25, 'merge_annotations': True, 'cover_gaps': True, 'resize_mode': 'stretch', } dataset = datasets.MSCOCO(**kwargs) for idx, res in enumerate(dataset.flow()): if not res: status = 'Skip' else: # convert label to rgb img, mask = res[0], res[1] rgb_label = one_hot_to_rgb(mask, dataset.PALETTE) # extract target filename filename_no_ext = os.path.splitext(img['file_name'])[0] lbl_path = os.path.join( target_dir, kwargs['data_type'], 'labels', '{}.png'.format(filename_no_ext) ) # convert array to PIL Image and save image to disk in png format (lossless) label = array_to_img(rgb_label) label.save(lbl_path) status = 'OK' msg = 'Processed {}/{} items. Status: {}'.format(idx + 1, dataset.num_items, status) print(msg, end='\r') sys.stdout.flush()