本文整理汇总了Python中Image.open方法的典型用法代码示例。如果您正苦于以下问题:Python Image.open方法的具体用法?Python Image.open怎么用?Python Image.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Image
的用法示例。
在下文中一共展示了Image.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def handle(self, *args, **options):
size = 128, 128
logging.info("Building avatar thumbnails")
for infile in glob("servo/uploads/avatars/*.jpg"):
logging.info(infile)
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(infile, "JPEG")
logging.info("Cleaning up unused attachments")
for infile in glob("servo/uploads/attachments/*"):
fn = infile.decode('utf-8')
fp = os.path.join("attachments", os.path.basename(fn))
try:
Attachment.objects.get(content=fp)
except Attachment.DoesNotExist:
os.remove(infile)
示例2: get_colors
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def get_colors(f, do_shuffle=True):
from numpy import array
try:
import Image
except Exception:
from PIL import Image
im = Image.open(f)
data = array(list(im.convert('RGB').getdata()),'float')/255.0
res = []
for rgb in data:
res.append(list(rgb))
if do_shuffle:
from numpy.random import shuffle
shuffle(res)
return res
示例3: imread
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def imread(name,flatten=0):
"""
Read an image file from a filename.
Parameters
----------
name : str
The file name to be read.
flatten : bool, optional
If True, flattens the color layers into a single gray-scale layer.
Returns
-------
imread : ndarray
The array obtained by reading image from file `name`.
Notes
-----
The image is flattened by calling convert('F') on
the resulting image object.
"""
im = Image.open(name)
return fromimage(im,flatten=flatten)
示例4: get_colors
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def get_colors(self,f):
import Image
from random import shuffle
scale = 1./255.
im = Image.open(f)
w,h = im.size
rgbim = im.convert('RGB')
res = []
for i in xrange(0,w):
for j in xrange(0,h):
r,g,b = rgbim.getpixel((i,j))
res.append((r*scale,g*scale,b*scale))
shuffle(res)
self.colors = res
self.ncolors = len(res)
示例5: _get_data
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def _get_data(url):
"""Helper function to get data over http or from a local file"""
if url.startswith('http://'):
# Try Python 2, use Python 3 on exception
try:
resp = urllib.urlopen(url)
encoding = resp.headers.dict.get('content-encoding', 'plain')
except AttributeError:
resp = urllib.request.urlopen(url)
encoding = resp.headers.get('content-encoding', 'plain')
data = resp.read()
if encoding == 'plain':
pass
elif encoding == 'gzip':
data = StringIO(data)
data = gzip.GzipFile(fileobj=data).read()
else:
raise RuntimeError('unknown encoding')
else:
with open(url, 'r') as fid:
data = fid.read()
fid.close()
return data
示例6: extract_line_count
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def extract_line_count(filename, target_dir):
# Extract the line count of a file
example_file = os.path.join(target_dir, filename)
lines = open(example_file).readlines()
start_row = 0
if lines and lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
line_iterator = iter(lines)
tokens = tokenize.generate_tokens(lambda: next(line_iterator))
check_docstring = True
erow_docstring = 0
for tok_type, _, _, (erow, _), _ in tokens:
tok_type = token.tok_name[tok_type]
if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
continue
elif ((tok_type == 'STRING') and check_docstring):
erow_docstring = erow
check_docstring = False
return erow_docstring+1+start_row, erow+1+start_row
示例7: load_image
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def load_image(self, idx):
filename = self.X[idx]
import Image
import ImageOps
# print "loading ", self.X[idx]
image = Image.open(self.X[idx])
width, height = image.size
if width > height:
delta2 = int((width - height)/2)
image = ImageOps.expand(image, border=(0, delta2, 0, delta2))
else:
delta2 = int((height - width)/2)
image = ImageOps.expand(image, border=(delta2, 0, delta2, 0))
image = image.resize((self.width, self.width), resample=Image.BICUBIC)
try:
imagenp = np.array(image.getdata()).reshape((self.width,self.width,3))
imagenp = imagenp.transpose((2,0,1)) # move color channels to beginning
except:
# print "reshape failure (black and white?)"
imagenp = self.load_image(np.random.randint(len(self.X)))
return imagenp.astype(theano.config.floatX)
示例8: extract_line_count
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def extract_line_count(filename, target_dir):
# Extract the line count of a file
example_file = os.path.join(target_dir, filename)
if six.PY2:
lines = open(example_file).readlines()
else:
lines = open(example_file, encoding='utf-8').readlines()
start_row = 0
if lines and lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
line_iterator = iter(lines)
tokens = tokenize.generate_tokens(lambda: next(line_iterator))
check_docstring = True
erow_docstring = 0
for tok_type, _, _, (erow, _), _ in tokens:
tok_type = token.tok_name[tok_type]
if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
continue
elif (tok_type == 'STRING') and check_docstring:
erow_docstring = erow
check_docstring = False
return erow_docstring+1+start_row, erow+1+start_row
示例9: build_from_dir
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def build_from_dir(directory, map_classes = None):
X = []
y = []
for c in os.listdir(directory):
for _file in os.listdir(os.path.join(directory, c)):
try:
image = Image.open(os.path.join(directory, c, _file))
image.verify()
X.append(os.path.join(directory, c, _file))
if map_classes:
y.append(map_classes[int(c)])
else:
y.append(c)
except IOError:
print "warning filename %s is not an image" % os.path.join(directory, c, _file)
X = np.array(X)
y = np.array(y)
return X, y
示例10: loadImage
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def loadImage():
xt = np.zeros((num_img, 3, 96, 96), dtype='float32')
i = 0
for file in glob.glob(url+"*.jpg"):
img = Image.open(file)
img = ImageOps.fit(img, (96, 96), Image.ANTIALIAS)
img = np.asarray(img, dtype = 'float32') / 255.
if(cmp(img.shape , (96,96,3)) == 0):
img = img.transpose(2,0,1).reshape(3, 96, 96)
xt[i]=img
else:
aux=to_rgb(img)
aux = aux.transpose(2,0,1).reshape(3, 96, 96)
xt[i]=aux
i = i + 1
return xt
示例11: loadiSUNTest
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def loadiSUNTest():
NumSample = 2000
names = loadNameListSUN(MAT_TEST_SUN,NumSample,'testing')
Xt = np.zeros((NumSample, 3, 96, 96), dtype='float32')
for i in range(NumSample):
img = Image.open('/imatge/jpan/work/iSUN/images/'+names[i]+'.jpg')
img = ImageOps.fit(img, (96, 96), Image.ANTIALIAS)
img = np.asarray(img, dtype = 'float32') / 255.
if(cmp(img.shape , (96,96,3)) == 0):
img = img.transpose(2,0,1).reshape(3, 96, 96)
Xt[i] = img
else:
print names[i]
aux=to_rgb(img)
aux = aux.transpose(2,0,1).reshape(3, 96, 96)
Xt[i]=aux
data_to_save = Xt
f = file('data_iSUN_Test.cPickle', 'wb')
pickle.dump(data_to_save, f, protocol=pickle.HIGHEST_PROTOCOL)
f.close()
示例12: _image_to_matrix
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def _image_to_matrix(img_data):
img = Image.open(StringIO(img_data)).convert('L')
w,h = img.size
# 生成矩阵
martix = []
for y in xrange(h / 2):
row = []
for x in xrange(w):
p1 = img.getpixel((x, y * 2))
p2 = img.getpixel((x, y * 2 + 1))
if p1 > 192 and p2 > 192:
row.append(0)
elif p1 > 192:
row.append(1)
elif p2 > 192:
row.append(2)
else:
row.append(3)
martix.append(row)
return martix
示例13: wms
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def wms(minx, miny, maxx, maxy, service, lyr, img, w, h):
"""Retrieve a wms map image from
the specified service and saves it as a PNG."""
wms = service
wms += "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&"
wms += "LAYERS=%s" % lyr
wms += "&STYLES=&"
wms += "SRS=EPSG:900913&"
wms += "BBOX=%s,%s,%s,%s&" % (minx, miny, maxx, maxy)
wms += "WIDTH=%s&" % w
wms += "HEIGHT=%s&" % h
wms += "FORMAT=image/png"
wmsmap = urllib.request.urlopen(wms)
with open(img + ".png", "wb") as f:
f.write(wmsmap.read())
# Nextbus agency and route ids
开发者ID:PacktPublishing,项目名称:Learning-Geospatial-Analysis-with-Python-Third-Edition,代码行数:19,代码来源:B13346_09_03-next.py
示例14: check_md5sum_change
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def check_md5sum_change(src_file):
"""Returns True if src_file has a different md5sum"""
src_md5 = get_md5sum(src_file)
src_md5_file = src_file + '.md5'
src_file_changed = True
if os.path.exists(src_md5_file):
with open(src_md5_file, 'r') as file_checksum:
ref_md5 = file_checksum.read()
if src_md5 == ref_md5:
src_file_changed = False
if src_file_changed:
with open(src_md5_file, 'w') as file_checksum:
file_checksum.write(src_md5)
return src_file_changed
示例15: _drawerToImage
# 需要导入模块: import Image [as 别名]
# 或者: from Image import open [as 别名]
def _drawerToImage(d2d):
try:
import Image
except ImportError:
from PIL import Image
sio = BytesIO(d2d.GetDrawingText())
return Image.open(sio)