Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
raise RuntimeError(
"Frame is %i bytes, but expected %i." % (len(s), framesize)
)
result = np.frombuffer(s, dtype=self._dtype).copy()
result = result.reshape((h, w, self._depth))
# t1 = time.time()
# print('etime', t1-t0)
# Store and return
self._lastread = result
return result, is_new
# --
class Writer(Format.Writer):
_write_gen = None
def _open(
self,
fps=10,
codec="libx264",
bitrate=None,
pixelformat="yuv420p",
ffmpeg_params=None,
input_params=None,
output_params=None,
ffmpeg_log_level="quiet",
quality=5,
macro_block_size=16,
):
'LA' ('L' with alpha), 'RGBX' (true color with padding) and 'RGBa'
(true color with premultiplied alpha).
When translating a color image to grayscale (mode 'L', 'I' or 'F'),
the library uses the ITU-R 601-2 luma transform::
L = R * 299/1000 + G * 587/1000 + B * 114/1000
as_gray : bool
If True, the image is converted using mode 'F'. When `mode` is
not None and `as_gray` is True, the image is first converted
according to `mode`, and the result is then "flattened" using
mode 'F'.
"""
class PillowFormat(Format):
"""
Base format class for Pillow formats.
"""
_pillow_imported = False
_Image = None
_modes = "i"
_description = ""
def __init__(self, *args, **kwargs):
super(PillowFormat, self).__init__(*args, **kwargs)
# Used to synchronize _init_pillow(), see #244
self._lock = threading.RLock()
@property
def plugin_id(self):
Image = self._init_pillow()
if request.mode[1] in (self.modes + "?"):
if self.plugin_id in Image.OPEN:
factory, accept = Image.OPEN[self.plugin_id]
if accept:
if request.firstbytes and accept(request.firstbytes):
return True
def _can_write(self, request):
Image = self._init_pillow()
if request.mode[1] in (self.modes + "?"):
if request.extension in self.extensions:
if self.plugin_id in Image.SAVE:
return True
class Reader(Format.Reader):
def _open(self, pilmode=None, as_gray=False):
Image = self.format._init_pillow()
try:
factory, accept = Image.OPEN[self.format.plugin_id]
except KeyError:
raise RuntimeError("Format %s cannot read images." % self.format.name)
self._fp = self._get_file()
self._im = factory(self._fp, "")
if hasattr(Image, "_decompression_bomb_check"):
Image._decompression_bomb_check(self._im.size)
# Save the raw mode used by the palette for a BMP because it may not be the number of channels
# When the data is read, imageio hands the palette to PIL to handle and clears the rawmode argument
# However, there is a bug in PIL with handling animated GIFs with a different color palette on each frame.
# This issue is resolved by using the raw palette data but the rawmode information is now lost. So we
# store the raw mode for later use
if self._im.palette and self._im.palette.dirty:
def _get_ffmpeg_api():
global _ffmpeg_api
if _ffmpeg_api is None:
try:
import imageio_ffmpeg
except ImportError:
raise ImportError(
"To use the imageio ffmpeg plugin you need to "
"'pip install imageio-ffmpeg'"
)
_ffmpeg_api = imageio_ffmpeg
return _ffmpeg_api
class FfmpegFormat(Format):
""" The ffmpeg format provides reading and writing for a wide range
of movie formats such as .avi, .mpeg, .mp4, etc. And also to read
streams from webcams and USB cameras.
To read from camera streams, supply "" as the filename,
where the "0" can be replaced with any index of cameras known to
the system.
To use this plugin, the ``imageio-ffmpeg`` library should be installed
(e.g. via pip). For most platforms this includes the ffmpeg executable.
One can use the ``IMAGEIO_FFMPEG_EXE`` environment variable to force
using a specific ffmpeg executable.
When reading from a video, the number of available frames is hard/expensive
to calculate, which is why its set to inf by default, indicating
"stream mode". To get the number of frames before having read them all,
with open(filename, "rb") as f:
first_bytes = read_n_bytes(f, 140)
return first_bytes[128:132] == b"DICM"
else:
return False
# Check
return request.firstbytes[128:132] == b"DICM"
def _can_write(self, request):
# We cannot save yet. May be possible if we will used pydicom as
# a backend.
return False
# --
class Reader(Format.Reader):
def _open(self, progress=True):
if not _dicom:
load_lib()
if os.path.isdir(self.request.filename):
# A dir can be given if the user used the format explicitly
self._info = {}
self._data = None
else:
# Read the given dataset now ...
try:
dcm = _dicom.SimpleDicomReader(self.request.get_file())
except _dicom.CompressedDicom as err:
if "JPEG" in str(err):
exe = get_dcmdjpeg_exe()
if not exe:
raise
self.array.shape = v["shape"]
return self.array
def get_meta(self):
return self.meta
class Image2D(Image):
pass
class Image3D(Image):
pass
class BsdfFormat(Format):
""" The BSDF format enables reading and writing of image data in the
BSDF serialization format. This format allows storage of images, volumes,
and series thereof. Data can be of any numeric data type, and can
optionally be compressed. Each image/volume can have associated
meta data, which can consist of any data type supported by BSDF.
By default, image data is lazily loaded; the actual image data is
not read until it is requested. This allows storing multiple images
in a single file and still have fast access to individual images.
Alternatively, a series of images can be read in streaming mode, reading
images as they are read (e.g. from http).
BSDF is a simple generic binary format. It is easy to extend and there
are standard extension definitions for 2D and 3D image data.
Read more at http://bsdf.io.
def _can_read(self, request):
if request.mode[1] in (self.modes + "?"):
# if request.extension in self.extensions:
# return True
if request.firstbytes.startswith(b"BSDF"):
return True
def _can_write(self, request):
if request.mode[1] in (self.modes + "?"):
if request.extension in self.extensions:
return True
# -- reader
class Reader(Format.Reader):
def _open(self, random_access=None):
# Validate - we need a BSDF file consisting of a list of images
# The list is typically a stream, but does not have to be.
assert self.request.firstbytes[:4] == b"BSDF", "Not a BSDF file"
# self.request.firstbytes[5:6] == major and minor version
if not (
self.request.firstbytes[6:15] == b"M\x07image2D"
or self.request.firstbytes[6:15] == b"M\x07image3D"
or self.request.firstbytes[6:7] == b"l"
):
pass # Actually, follow a more duck-type approach ...
# raise RuntimeError('BSDF file does not look like an '
# 'image container.')
# Set options. If we think that seeking is allowed, we lazily load
# blobs, and set streaming to False (i.e. the whole file is read,
# but we skip over binary blobs), so that we subsequently allow
"c:\\Program Files",
"c:\\Program Files\\dcmtk",
"c:\\Program Files (x86)\\dcmtk",
):
filename = os.path.join(dir, fname)
if os.path.isfile(filename):
return filename
try:
subprocess.check_call([fname, "--version"])
return fname
except Exception:
return None
class DicomFormat(Format):
""" A format for reading DICOM images: a common format used to store
medical image data, such as X-ray, CT and MRI.
This format borrows some code (and ideas) from the pydicom project,
and (to the best of our knowledge) has the same limitations as
pydicom with regard to the type of files that it can handle. However,
only a predefined subset of tags are extracted from the file. This allows
for great simplifications allowing us to make a stand-alone reader, and
also results in a much faster read time. We plan to allow reading all
tags in the future (by using pydicom).
This format provides functionality to group images of the same
series together, thus extracting volumes (and multiple volumes).
Using volread will attempt to yield a volume. If multiple volumes
are present, the first one is given. Using mimread will simply yield
all images in the given directory (not taking series into account).
from ..core import Format, read_n_bytes, image_as_uint
logger = logging.getLogger(__name__)
_swf = None # lazily loaded in lib()
def load_lib():
global _swf
from . import _swf
return _swf
class SWFFormat(Format):
""" Shockwave flash (SWF) is a media format designed for rich and
interactive animations. This plugin makes use of this format to
store a series of images in a lossless format with good compression
(zlib). The resulting images can be shown as an animation using
a flash player (such as the browser).
SWF stores images in RGBA format. RGB or grayscale images are
automatically converted. SWF does not support meta data.
Parameters for reading
----------------------
loop : bool
If True, the video will rewind as soon as a frame is requested
beyond the last frame. Otherwise, IndexError is raised. Default False.
Parameters for saving
""" Plugin for animated GIF, using the freeimage lib as a backend.
"""
from __future__ import absolute_import, print_function, division
import numpy as np
from imageio import formats
from imageio.core import Format
from ._freeimage import fi, IO_FLAGS
# The freetype image format for GIF is 25
FIF = 25
class AnimatedGifFormat(Format):
""" A format for reading and writing animated GIF, based on the
Freeimage library.
Parameters for reading
----------------------
playback : bool
'Play' the GIF to generate each frame (as 32bpp) instead of
returning raw frame data when loading. Default True.
Parameters for saving
---------------------
loop : int
The number of iterations. Default 0 (meaning loop indefinitely)
This argumen is not implemented yet :(
duration : {float, list}
The duration (in seconds) of each frame. Either specify one value