Python PIL.Image 模块,ROTATE_90 实例源码
我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用PIL.Image.ROTATE_90。
def font_variant(self, font=None, size=None, index=None, encoding=None):
"""
Create a copy of this FreeTypeFont object,
using any specified arguments to override the settings.
Parameters are identical to the parameters used to initialize this
object.
:return: A FreeTypeFont object.
"""
return FreeTypeFont(font=self.path if font is None else font,
size=self.size if size is None else size,
index=self.index if index is None else index,
encoding=self.encoding if encoding is None else
encoding)
##
# Wrapper that creates a transposed font from any existing font
# object.
#
# @param font A font object.
# @param orientation An optional orientation. If given,this should
# be one of Image.FLIP_LEFT_RIGHT,Image.FLIP_TOP_BottOM,
# Image.ROTATE_90,Image.ROTATE_180,or Image.ROTATE_270.
def image_transpose_exif(im):
exif_orientation_tag = 0x0112 # contains an integer,1 through 8
exif_transpose_sequences = [ # corresponding to the following
[],
[Image.FLIP_LEFT_RIGHT],
[Image.ROTATE_180],
[Image.FLIP_TOP_BottOM],
[Image.FLIP_LEFT_RIGHT, Image.ROTATE_90],
[Image.ROTATE_270],
[Image.FLIP_TOP_BottOM,
[Image.ROTATE_90],
]
try:
if im._getexif() is not None:
seq = exif_transpose_sequences[im._getexif()[exif_orientation_tag] - 1]
return functools.reduce(lambda im, op: im.transpose(op), seq, im)
else:
return im
except KeyError:
return im
def image_transpose_exif(im):
exif_orientation_tag = 0x0112 # contains an integer, im)
else:
return im
except KeyError:
return im
def handle_exif(image_file):
with Image.open(image_file) as image:
orientation_key = 274
exif = image._getexif()
format = image.format
if exif and orientation_key in exif:
orientation = exif[orientation_key]
rotate_values = {
3: Image.ROTATE_180,
6: Image.ROTATE_270,
8: Image.ROTATE_90
}
if orientation in rotate_values:
image = image.transpose(rotate_values[orientation])
image_io = BytesIO()
image.save(image_io, format)
return image_io
def getsize(self, text):
w, h = self.font.getsize(text)
if self.orientation in (Image.ROTATE_90, Image.ROTATE_270):
return h, w
return w, h
def __getitem__(self, index):
Cpath, Spath = self.imgs[index][0], self.imgs[index][1]
Cimg, Simg = color_loader(Cpath), grey_loader(Spath)
Cimg, Simg = RandomCrop(511)(Cimg, Simg)
if random.random() < 0.5:
Cimg, Simg = Cimg.transpose(Image.FLIP_LEFT_RIGHT), Simg.transpose(Image.FLIP_LEFT_RIGHT)
if random.random() < 0.5:
Cimg, Simg = Cimg.transpose(Image.FLIP_TOP_BottOM), Simg.transpose(Image.FLIP_TOP_BottOM)
if random.random() < 0.5:
Cimg, Simg = Cimg.transpose(Image.ROTATE_90), Simg.transpose(Image.ROTATE_90)
Cimg, Vimg, Simg = self.transform(Cimg), self.vtransform(Cimg), self.stransform(Simg)
return Cimg, Simg
def __getitem__(self, Spath = self.imgs[index]
Cimg, sketch_loader(Spath)
Cimg, Simg.transpose(Image.FLIP_TOP_BottOM)
# if random.random() < 0.5:
# Vimg = Vimg.transpose(Image.ROTATE_90)
Cimg, Simg
def __getitem__(self, sketch_loader(Spath)
if random.random() < 0.5:
Cimg, Simg.transpose(Image.FLIP_LEFT_RIGHT)
Vimg = Cimg
if random.random() < 0.5:
Vimg = Vimg.transpose(Image.FLIP_LEFT_RIGHT)
# if random.random() < 0.5:
# Vimg = Vimg.transpose(Image.ROTATE_90)
Cimg, self.vtransform(Vimg), Simg
def __getitem__(self, Simg.transpose(Image.FLIP_LEFT_RIGHT)
Vimg = Cimg
# if random.random() < 0.5:
# Vimg = Vimg.transpose(Image.FLIP_LEFT_RIGHT)
# if random.random() < 0.5:
# Vimg = Vimg.transpose(Image.ROTATE_90)
Cimg, Simg
def __getitem__(self, self.imgs[index][random.randint(1, 3)]
Cimg, Simg
def __init__(self, font, orientation=None):
"""
Wrapper that creates a transposed font from any existing font
object.
:param font: A font object.
:param orientation: An optional orientation. If given,this should
be one of Image.FLIP_LEFT_RIGHT,
Image.ROTATE_90,or Image.ROTATE_270.
"""
self.font = font
self.orientation = orientation # any 'transpose' argument,or None
def transpose(self, opts): ###############################################
self.logger.debug("Transposing image %s: %s"
% (self.file_path, str(opts)))
# Parse possible arguments
num_args = 0
if "flipvert" in opts:
method = Image.FLIP_LEFT_RIGHT
num_args += 1
if "fliphorz" in opts:
method = Image.FLIP_TOP_BottOM
num_args += 1
if "rotate90" in opts:
method = Image.ROTATE_90
num_args += 1
if "rotate180" in opts:
method = Image.ROTATE_180
num_args += 1
if "rotate270" in opts:
method = Image.ROTATE_270
num_args += 1
if num_args != 1:
raise DirpyUserError(
"Transpose requires exactly one option: %s" % str(opts))
# Now rotate
try:
self.im_in = self.im_in.transpose(method)
self.out_x, self.out_y = self.im_in.size
self.modified = True
except Exception as e:
raise DirpyFatalError(
"Error transposing image %s: %s" % (self.file_path,e))
# Write an image to a BytesIO output buffer
def __generateRotatedImage(self, image):
"""Use the current rotation of this `ImageFile` to rotate :class:`PIL.Image`.
:param image: The input image.
:return image: The output image."""
if self.rotation == 1:
image = image.transpose(Image.ROTATE_90)
elif self.rotation == 2:
image = image.transpose(Image.ROTATE_180)
elif self.rotation == 3:
image = image.transpose(Image.ROTATE_270)
return image
def take_image(self):
snapshot_url = self._settings.global_get(["webcam", "snapshot"])
self._logger.debug("Snapshot URL: " + str(snapshot_url))
data = None
if snapshot_url:
try:
r = requests.get(snapshot_url)
data = r.content
except Exception as e:
return None
flipH = self._settings.global_get(["webcam", "flipH"])
flipV = self._settings.global_get(["webcam", "flipV"])
rotate= self._settings.global_get(["webcam", "rotate90"])
if flipH or flipV or rotate:
image = Image.open(StringIO.StringIO(data))
if flipH:
image = image.transpose(Image.FLIP_LEFT_RIGHT)
if flipV:
image = image.transpose(Image.FLIP_TOP_BottOM)
if rotate:
image = image.transpose(Image.ROTATE_90)
output = StringIO.StringIO()
image.save(output, format="JPEG")
data = output.getvalue()
output.close()
return data
def image_transpose_exif(im):
exif_orientation_tag = 0x0112 # contains an integer,1 through 8
exif_transpose_sequences = [ # corresponding to the following
[],
]
try:
seq = exif_transpose_sequences[im._getexif()[exif_orientation_tag] - 1]
except Exception:
return im
else:
return functools.reduce(lambda im, im)
# def average_color_pixels(image,pixels):
# r,g,b = 0,0
# for pixel in pixels:
# x,y = pixel
# cr,cg,cb = image.getpixel((x,y))
# r+=cr
# g+=cg
# b+=cb
# total = len(pixels)
# return (r/total,g/total,b/total)
def exif_orientation(im):
try:
exif = im._getexif()
except Exception:
# There are many ways that _getexif fails,we're just going to blanket
# cover them all.
return im
if exif is None:
return im
orientation = exif.get(0x0112)
if orientation == 2:
im = im.transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 3:
im = im.transpose(Image.ROTATE_180)
elif orientation == 4:
im = im.transpose(Image.FLIP_TOP_BottOM)
elif orientation == 5:
im = im.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 6:
im = im.transpose(Image.ROTATE_270)
elif orientation == 7:
im = im.transpose(Image.ROTATE_90).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 8:
im = im.transpose(Image.ROTATE_90)
return im
# Low-tech approach to work around the too strict URLValidator.
# Context: https://code.djangoproject.com/ticket/20264
# replace() isn't super elegant,but I prefer this to having to copy/paste the whole big regexp
# soup from URLValidator so that I can add one underscore...
def process_image(data, mime_type):
stream = io.BytesIO(data)
try:
img = Image.open(stream)
except OSError:
raise ValueError('Invalid image data')
if mime_type == 'image/jpeg' and img.format == 'JPEG':
format = "JPEG"
subsampling = 'keep'
# check exif information for orientation
if hasattr(img, '_getexif'):
x = img._getexif()
if x and EXIF_ORIENTATION in x and x[EXIF_ORIENTATION] > 1 and x[EXIF_ORIENTATION] < 9:
orientation = x[EXIF_ORIENTATION]
subsampling = get_sampling(img)
if orientation == 2:
# Vertical Mirror
img = img.transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 3:
# Rotation 180°
img = img.transpose(Image.ROTATE_180)
elif orientation == 4:
# Horizontal Im
img = img.transpose(Image.FLIP_TOP_BottOM)
elif orientation == 5:
# Horizontal Im + Rotation 90° ccw
img = img.transpose(Image.FLIP_TOP_BottOM).transpose(Image.ROTATE_90)
elif orientation == 6:
# Rotation 270°
img = img.transpose(Image.ROTATE_270)
elif orientation == 7:
# Horizontal Im + Rotation 270°
img = img.transpose(Image.FLIP_TOP_BottOM).transpose(Image.ROTATE_270)
elif orientation == 8:
# Rotation 90°
img = img.transpose(Image.ROTATE_90)
save_kwargs = {'subsampling': subsampling, 'quality': 85}
elif mime_type == 'image/png' and img.format == 'PNG':
format = "PNG"
save_kwargs = {'icc_profile': img.info.get("icc_profile")}
else:
raise ValueError('Unsupported image format')
if img.size[0] > 512 or img.size[1] > 512:
img.thumbnail((512, 512))
stream = io.BytesIO()
img.save(stream, format=format, optimize=True, **save_kwargs)
data = stream.getbuffer().tobytes()
hasher = hashlib.md5()
hasher.update(data)
cache_hash = hasher.hexdigest()
return data, cache_hash, format
def process_image(data, mime_type):
stream = io.BytesIO(data)
try:
img = Image.open(stream)
except OSError:
raise JSONHTTPError(400, body={'errors': [{'id': 'bad_arguments', 'message': 'Invalid image data'}]})
if mime_type == 'image/jpeg' and img.format == 'JPEG':
format = "JPEG"
subsampling = 'keep'
# check exif information for orientation
if hasattr(img, 'quality': 85}
elif mime_type == 'image/png' and img.format == 'PNG':
format = "PNG"
save_kwargs = {'icc_profile': img.info.get("icc_profile")}
else:
raise JSONHTTPError(400, 'message': 'Unsupported image format'}]})
if img.size[0] > 512 or img.size[1] > 512:
img.thumbnail((512, format
def rotate_image(input_file, input_Box):
prefix = os.path.splitext(input_file)[0]
x1 = input_Box[0]["x1"]
y1 = input_Box[0]["y1"]
x2 = input_Box[0]["x2"]
y2 = input_Box[0]["y2"]
im = Image.open(input_file)
im1 = im.transpose(Image.ROTATE_90)
im2 = im.transpose(Image.ROTATE_180)
im3 = im.transpose(Image.ROTATE_270)
output_file = [
prefix + "_rotate_1.bmp",
prefix + "_rotate_2.bmp",
prefix + "_rotate_3.bmp",
]
output_Box = [
{
"x1": y1,
"x2": y2,
"y1": SIZE - 1 - x1,
"y2": SIZE - 1 - x2,
},
{
"x1": SIZE - 1 - x1,
"x2": SIZE - 1 - x2,
"y1": SIZE - 1 - y1,
"y2": SIZE - 1 - y2,
{
"x1": SIZE - 1 - y1,
"x2": SIZE - 1 - y2,
"y1": x1,
"y2": x2,
]
im1.save(output_file[0])
im2.save(output_file[1])
im3.save(output_file[2])
# draw_Box(im1,output_Box[0]).save(output_file[0])
# draw_Box(im2,output_Box[1]).save(output_file[1])
# draw_Box(im3,output_Box[2]).save(output_file[2])
return output_file, output_Box
def _upload_snapshot(self):
self._logger.debug("_upload_snapshot")
upload_type = 'idle'
if self._cloud_print and self._job_id != '123' and (self._printer.is_printing() or self._printer.is_paused()):
upload_type = 'printing'
self._logger.debug("upload_type {}".format(upload_type))
if not self._ensure_upload_url(upload_type):
return
try:
loc = self._upload_location[upload_type]
r = requests.get(self._snapshot_url, timeout=5)
r.raise_for_status()
except Exception:
self._logger.exception("Could not capture image from {}".format(self._snapshot_url))
return
try:
image_bytes = r.content
image_size = len(image_bytes)
if self._image_transpose or image_size > self._max_image_size:
self._logger.debug("Recompressing snapshot to smaller size")
buf = StringIO()
buf.write(image_bytes)
image = Image.open(buf)
image.thumbnail((640, 480))
if self._settings.global_get(["webcam", "flipH"]):
image = image.transpose(Image.FLIP_LEFT_RIGHT)
if self._settings.global_get(["webcam", "flipV"]):
image = image.transpose(Image.FLIP_TOP_BottOM)
if self._settings.global_get(["webcam", "rotate90"]):
image = image.transpose(Image.ROTATE_90)
image_bytes = StringIO()
image.save(image_bytes, format="jpeg")
image_bytes.seek(0, 2)
new_image_size = image_bytes.tell()
image_bytes.seek(0)
self._logger.debug("Image transcoded from size {} to {}".format(image_size, new_image_size))
image_size = new_image_size
if image_size == 0:
self._logger.debug("Image content is length 0 from {},not uploading to PolarCloud".format(self._snapshot_url))
return
p = requests.post(loc['url'], data=loc['fields'], files={'file': ('image.jpg', image_bytes)})
p.raise_for_status()
self._logger.debug("{}: {}".format(p.status_code, p.content))
self._logger.debug("Image captured from {}".format(self._snapshot_url))
except Exception:
self._logger.exception("Could not post snapshot to PolarCloud")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。