本文整理汇总了Python中PIL.Image.open方法的典型用法代码示例。如果您正苦于以下问题:Python Image.open方法的具体用法?Python Image.open怎么用?Python Image.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PIL.Image
的用法示例。
在下文中一共展示了Image.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: loop
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def loop():
print('Looping through all images in folder {}\n'
'CRL+C to skip image'.format(folder_path))
try:
for img_file in os.listdir(folder_path):
if img_file.endswith(icon_extension):
print('Drawing image: {}'.format(folder_path + img_file))
img = Image.open(folder_path + img_file)
draw_animation(img)
else:
print('Not using this file, might be not an image: {}'.format(img_file))
except KeyboardInterrupt:
unicorn.off()
unicorn.off()
示例2: weather_icons
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def weather_icons():
try:
if argv[1] == 'loop':
loop()
elif argv[1] in os.listdir(folder_path):
print('Drawing Image: {}'.format(argv[1]))
img = Image.open(folder_path + argv[1])
draw_animation(img)
unicorn.off()
else:
help()
except IndexError:
help()
示例3: screenshot
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def screenshot(self, name):
'''
screenshot()
Takes a screenshot of the browser
'''
if do_crop:
print('cropping screenshot')
# Grab screenshot rather than saving
im = self.browser.get_screenshot_as_png()
im = Image.open(BytesIO(im))
# Crop to specifications
im = im.crop((crop_x, crop_y, crop_width, crop_height))
im.save(name)
else:
self.browser.save_screenshot(name)
print("success saving screenshot: %s" % name)
return name
示例4: output_coords
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def output_coords():
# Open the file to output the co-ordinates to
f1 = open('./setup_data.py', 'w+')
# Print the dictionary data to the file
print >>f1, 'boxes = ['
for i in range(Boxes.length()):
c = Boxes.get(i).get_output(SelWindow.bgcoords)
if c != None:
o = (i)
print >>f1, c, ','
print >>f1, ']'
print 'INFO: Box data saved in file boxdata.py.'
tkMessageBox.showinfo("Pi Setup", "Box data saved in file.")
# -----------------------------------------------------------------------------
# Main Program
# -----------------------------------------------------------------------------
示例5: __init__
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.master = master
self.init_window()
self.about_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/LPHK-banner.png"))
self.info_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/info.png"))
self.warning_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/warning.png"))
self.error_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/error.png"))
self.alert_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/alert.png"))
self.scare_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/scare.png"))
self.grid_drawn = False
self.grid_rects = [[None for y in range(9)] for x in range(9)]
self.button_mode = "edit"
self.last_clicked = None
self.outline_box = None
示例6: download_image
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def download_image(image_id, url, x1, y1, x2, y2, output_dir):
"""Downloads one image, crops it, resizes it and saves it locally."""
output_filename = os.path.join(output_dir, image_id + '.png')
if os.path.exists(output_filename):
# Don't download image if it's already there
return True
try:
# Download image
url_file = urlopen(url)
if url_file.getcode() != 200:
return False
image_buffer = url_file.read()
# Crop, resize and save image
image = Image.open(BytesIO(image_buffer)).convert('RGB')
w = image.size[0]
h = image.size[1]
image = image.crop((int(x1 * w), int(y1 * h), int(x2 * w),
int(y2 * h)))
image = image.resize((299, 299), resample=Image.ANTIALIAS)
image.save(output_filename)
except IOError:
return False
return True
示例7: _prepare_sample_data
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def _prepare_sample_data(self, submission_type):
"""Prepares sample data for the submission.
Args:
submission_type: type of the submission.
"""
# write images
images = np.random.randint(0, 256,
size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)
for i in range(BATCH_SIZE):
Image.fromarray(images[i, :, :, :]).save(
os.path.join(self._sample_input_dir, IMAGE_NAME_PATTERN.format(i)))
# write target class for targeted attacks
if submission_type == 'targeted_attack':
target_classes = np.random.randint(1, 1001, size=[BATCH_SIZE])
target_class_filename = os.path.join(self._sample_input_dir,
'target_class.csv')
with open(target_class_filename, 'w') as f:
for i in range(BATCH_SIZE):
f.write((IMAGE_NAME_PATTERN + ',{1}\n').format(i, target_classes[i]))
示例8: _load_dataset_clipping
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def _load_dataset_clipping(self, dataset_dir, epsilon):
"""Helper method which loads dataset and determines clipping range.
Args:
dataset_dir: location of the dataset.
epsilon: maximum allowed size of adversarial perturbation.
"""
self.dataset_max_clip = {}
self.dataset_min_clip = {}
self._dataset_image_count = 0
for fname in os.listdir(dataset_dir):
if not fname.endswith('.png'):
continue
image_id = fname[:-4]
image = np.array(
Image.open(os.path.join(dataset_dir, fname)).convert('RGB'))
image = image.astype('int32')
self._dataset_image_count += 1
self.dataset_max_clip[image_id] = np.clip(image + epsilon,
0,
255).astype('uint8')
self.dataset_min_clip[image_id] = np.clip(image - epsilon,
0,
255).astype('uint8')
示例9: __init__
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def __init__(self, filename):
"""Initializes instance of DatasetMetadata."""
self._true_labels = {}
self._target_classes = {}
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
try:
row_idx_image_id = header_row.index('ImageId')
row_idx_true_label = header_row.index('TrueLabel')
row_idx_target_class = header_row.index('TargetClass')
except ValueError:
raise IOError('Invalid format of dataset metadata.')
for row in reader:
if len(row) < len(header_row):
# skip partial or empty lines
continue
try:
image_id = row[row_idx_image_id]
self._true_labels[image_id] = int(row[row_idx_true_label])
self._target_classes[image_id] = int(row[row_idx_target_class])
except (IndexError, ValueError):
raise IOError('Invalid format of dataset metadata')
示例10: load_images
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def load_images(input_dir, metadata_file_path, batch_shape):
"""Retrieve numpy arrays of images and labels, read from a directory."""
num_images = batch_shape[0]
with open(metadata_file_path) as input_file:
reader = csv.reader(input_file)
header_row = next(reader)
rows = list(reader)
row_idx_image_id = header_row.index('ImageId')
row_idx_true_label = header_row.index('TrueLabel')
images = np.zeros(batch_shape)
labels = np.zeros(num_images, dtype=np.int32)
for idx in xrange(num_images):
row = rows[idx]
filepath = os.path.join(input_dir, row[row_idx_image_id] + '.png')
with tf.gfile.Open(filepath, 'rb') as f:
image = np.array(
Image.open(f).convert('RGB')).astype(np.float) / 255.0
images[idx, :, :, :] = image
labels[idx] = int(row[row_idx_true_label])
return images, labels
示例11: __getitem__
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def __getitem__(self, index):
"""This function returns a tuple that is further passed to collate_fn
"""
vocab = self.vocab
root = self.root
ann_id = self.ids[index]
img_id = ann_id[0]
caption = self.dataset[img_id]['sentences'][ann_id[1]]['raw']
path = self.dataset[img_id]['filename']
image = Image.open(os.path.join(root, path)).convert('RGB')
if self.transform is not None:
image = self.transform(image)
# Convert caption (string) to word ids.
tokens = nltk.tokenize.word_tokenize(
str(caption).lower())
caption = []
caption.append(vocab('<start>'))
caption.extend([vocab(token) for token in tokens])
caption.append(vocab('<end>'))
target = torch.Tensor(caption)
return image, target, index, img_id
示例12: __init__
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def __init__(self, data_path, data_split, vocab, cap_suffix='caps'):
self.vocab = vocab
loc = data_path + '/'
# Captions
self.captions = []
with open(loc+'%s_%s.txt' % (data_split, cap_suffix), 'rb') as f:
for line in f:
tmp = line.strip()
if type(tmp) == bytes:
tmp = bytes.decode(tmp)
self.captions.append(tmp)
# Image features
self.images = np.load(loc+'%s_ims.npy' % data_split)
self.length = len(self.captions)
# rkiros data has redundancy in images, we divide by 5, 10crop doesn't
if self.images.shape[0] != self.length:
self.im_div = 5
else:
self.im_div = 1
# the development set for coco is large and so validation would be slow
if data_split == 'dev':
self.length = 5000
示例13: get_data
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def get_data(img_path):
"""get the (1, 3, h, w) np.array data for the supplied image
Args:
img_path (string): the input image path
Returns:
np.array: image data in a (1, 3, h, w) shape
"""
mean = np.array([123.68, 116.779, 103.939]) # (R,G,B)
img = Image.open(img_path)
img = np.array(img, dtype=np.float32)
reshaped_mean = mean.reshape(1, 1, 3)
img = img - reshaped_mean
img = np.swapaxes(img, 0, 2)
img = np.swapaxes(img, 1, 2)
img = np.expand_dims(img, axis=0)
return img
示例14: __init__
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def __init__(self, root_dir, flist_name,
rgb_mean = (117, 117, 117),
cut_off_size = None,
data_name = "data",
label_name = "softmax_label"):
super(FileIter, self).__init__()
self.root_dir = root_dir
self.flist_name = os.path.join(self.root_dir, flist_name)
self.mean = np.array(rgb_mean) # (R, G, B)
self.cut_off_size = cut_off_size
self.data_name = data_name
self.label_name = label_name
self.num_data = len(open(self.flist_name, 'r').readlines())
self.f = open(self.flist_name, 'r')
self.data, self.label = self._read()
self.cursor = -1
示例15: get_caltech101_data
# 需要导入模块: from PIL import Image [as 别名]
# 或者: from PIL.Image import open [as 别名]
def get_caltech101_data():
url = "https://s3.us-east-2.amazonaws.com/mxnet-public/101_ObjectCategories.tar.gz"
dataset_name = "101_ObjectCategories"
data_folder = "data"
if not os.path.isdir(data_folder):
os.makedirs(data_folder)
tar_path = mx.gluon.utils.download(url, path=data_folder)
if (not os.path.isdir(os.path.join(data_folder, "101_ObjectCategories")) or
not os.path.isdir(os.path.join(data_folder, "101_ObjectCategories_test"))):
tar = tarfile.open(tar_path, "r:gz")
tar.extractall(data_folder)
tar.close()
print('Data extracted')
training_path = os.path.join(data_folder, dataset_name)
testing_path = os.path.join(data_folder, "{}_test".format(dataset_name))
return training_path, testing_path