Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`
767612
def _ll_pre_transform(self, train_tfm:List[Callable], valid_tfm:List[Callable]):
    ""
    self.train.x.after_open = compose(train_tfm)
    self.valid.x.after_open = compose(valid_tfm)
    return self
852095
def __prepare(self, filestem, pos, neg, b):
        
        posFile = open('%s/%s.f' % (self.tmpdir, filestem), 'w')
        negFile = open('%s/%s.n' % (self.tmpdir, filestem), 'w')
        bFile = open('%s/%s.b' % (self.tmpdir, filestem), 'w')

        posFile.write(pos)
        negFile.write(neg)
        bFile.write(b)

        posFile.close()
        negFile.close()
        bFile.close()
467163
def _generate_examples(self, archive, validation_labels=None):
    """"""
    if validation_labels:  # Validation split
      for example in self._generate_examples_validation(archive,
                                                        validation_labels):
        yield example
    # Training split. Main archive contains archives names after a synset noun.
    # Each sub-archive contains pictures associated to that synset.
    for fname, fobj in archive:
      label = fname[:-4]  # fname is something like 'n01632458.tar'
      # TODO(b/117643231): in py3, the following lines trigger tarfile module
      # to call `fobj.seekable()`, which Gfile doesn't have. We should find an
      # alternative, as this loads ~150MB in RAM.
      fobj_mem = io.BytesIO(fobj.read())
      for image_fname, image_fobj in tfds.download.iter_archive(
          fobj_mem, tfds.download.ExtractMethod.TAR):
        yield {
            'file_name': image_fname,
            'image': image_fobj,
            'label': label,
        }
1142532
def replace(input, **pars):
    
    pixvalue = pars.get('pixvalue', np.nan)
    if pixvalue is None: pixvalue = np.nan # insure that None == np.nan

    newvalue = pars.get('newvalue', 0.0)
    ext = pars.get('ext',None)
    if ext in ['',' ','None',None]:
        ext = None

    files = parseinput.parseinput(input)[0]

    for f in files:
        fimg = fits.open(f, mode='update', memmap=False)

        if ext is None:
            # replace pixels in ALL extensions
            extn = [i for i in fimg]
        else:
            if type(ext) == type([]):
                extn = [fimg[e] for e in ext]
            else:
                extn = [fimg[ext]]

        for e in extn:
            if e.data is not None and e.is_image: # ignore empty Primary HDUs
                print("Converting {}[{},{}] value of {} to {}".format(
                        f,e.name,e.ver,pixvalue,newvalue))
                if np.isnan(pixvalue):
                    e.data[np.isnan(e.data)] = newvalue
                else:
                    e.data[np.where(e.data == pixvalue)] = newvalue

        fimg.close()
1175827
def tonet(self, outfile):
        
        
        self.checkforpilimage()
        if self.verbose :
            print "Writing image to %s...\n%i x %i pixels, mode %s" % (outfile, self.pilimage.size[0], self.pilimage.size[1], self.pilimage.mode)
        self.pilimage.save(outfile, "PNG")
371970
def rebase(self, qemu_img, base_image):
        

        if not os.path.exists(base_image):
            raise FileNotFoundError(base_image)
        command = [qemu_img, "rebase", "-u", "-b", base_image, self._path]
        process = yield from asyncio.create_subprocess_exec(*command)
        retcode = yield from process.wait()
        if retcode != 0:
            raise Qcow2Error("Could not rebase the image")
        self._reload()
1322833
def check_pil(func):
    
    def __wrapper(*args, **kwargs):
        root = kwargs.get('root')
        if not Image:
            if root and root.get_opt('warn'):
                warn("Images manipulation require PIL")
            return 'none'
        return func(*args, **kwargs)
    return __wrapper
1152748
def png_workaround(self, filepath, width=1200, height=800):
        
        sys.stdout = sys.__stdout__
        cmd.feedback('disable', 'movie', 'everything')
        cmd.viewport(width, height)
        cmd.zoom('visible', 1.5)  # Adapt the zoom to the viewport
        cmd.set('ray_trace_frames', 1)  # Frames are raytraced before saving an image.
        cmd.mpng(filepath, 1, 1)  # Use batch png mode with 1 frame only
        cmd.mplay()  # cmd.mpng needs the animation to 'run'
        cmd.refresh()
        originalfile = "".join([filepath, '0001.png'])
        newfile = "".join([filepath, '.png'])

        #################################################
        # Wait for file for max. 1 second and rename it #
        #################################################

        attempts = 0
        while not os.path.isfile(originalfile) and attempts <= 10:
            sleep(0.1)
            attempts += 1
        if os.name == 'nt':  # In Windows, make sure there is no file of the same name, cannot be overwritten as in Unix
            if os.path.isfile(newfile):
                os.remove(newfile)
        os.rename(originalfile, newfile)  # Remove frame number in filename

        #  Check if imagemagick is available and crop + resize the images
        if subprocess.call("type convert", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0:
            attempts, ecode = 0, 1
            # Check if file is truncated and wait if that's the case
            while ecode != 0 and attempts <= 10:
                ecode = subprocess.call(['convert', newfile, '/dev/null'], stdout=open('/dev/null', 'w'),
                                        stderr=subprocess.STDOUT)
                sleep(0.1)
                attempts += 1
            trim = 'convert -trim ' + newfile + ' -bordercolor White -border 20x20 ' + newfile + ';'  # Trim the image
            os.system(trim)
            getwidth = 'w=`convert ' + newfile + ' -ping -format "%w" info:`;'  # Get the width of the new image
            getheight = 'h=`convert ' + newfile + ' -ping -format "%h" info:`;'  # Get the hight of the new image
            newres = 'if [ "$w" -gt "$h" ]; then newr="${w%.*}x$w"; else newr="${h%.*}x$h"; fi;'  # Set quadratic ratio
            quadratic = 'convert ' + newfile + ' -gravity center -extent "$newr" ' + newfile  # Fill with whitespace
            os.system(getwidth + getheight + newres + quadratic)
        else:
            sys.stderr.write('Imagemagick not available. Images will not be resized or cropped.')
77419
def encode_example(self, image_or_path_or_fobj):
    """"""
    if isinstance(image_or_path_or_fobj, np.ndarray):
      encoded_image = self._encode_image(image_or_path_or_fobj)
    elif isinstance(image_or_path_or_fobj, six.string_types):
      with tf.io.gfile.GFile(image_or_path_or_fobj, 'rb') as image_f:
        encoded_image = image_f.read()
    else:
      encoded_image = image_or_path_or_fobj.read()
    return encoded_image
1158036
def check_image_file_header(filename):
  """"""
  with tf.gfile.Open(filename, 'rb') as f:
    magic = read32(f)
    read32(f)  # num_images, unused
    rows = read32(f)
    cols = read32(f)
    if magic != 2051:
      raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
                                                                     f.name))
    if rows != 28 or cols != 28:
      raise ValueError(
          'Invalid MNIST file %s: Expected 28x28 images, found %dx%d' %
          (f.name, rows, cols))
864917
function imageTtfTextErrorHandler($errno, $errstr) {
        // log the error
        Log::addErrorLog('Image Builder error: >' . $errno . '/' . $errstr . '< while processing file >' . $this->media->getServerFilename() . '<');
    
        // change value of useTTF to false so the fallback watermarking can be used.
        $this->use_ttf = false;
    
        return true;
    }
557483
def validate(self, instance, value):
        
        # Pass if already validated
        if getattr(value, '__valid__', False):
            return value
        # Validate that value is PNG
        if isinstance(value, png.Image):
            pass
        else:
            value = super(ImagePNG, self).validate(instance, value)
            try:
                png.Reader(value).validate_signature()
            except png.FormatError:
                self.error(instance, value, extra='Open file is not PNG.')
            value.seek(0)
        # Write input to new bytestream
        output = BytesIO()
        output.name = self.filename
        output.__valid__ = True
        if isinstance(value, png.Image):
            value.save(output)
        else:
            fid = value
            fid.seek(0)
            output.write(fid.read())
            fid.close()
        output.seek(0)
        return output
21532
def with_tmpfile
      path = [@file, $$.to_s(36), Thread.current.object_id.to_s(36)].join
      file = File.open(path, 'wb')
      yield(path, file)
    ensure
      file.close unless file.closed?
      File.unlink(path) if File.exists?(path)
    end
467346
def to_image_type(image_type):
    '''
        
    '''
    if image_type is None: return None
    if isinstance(image_type, type) and issubclass(image_type, ImageType): return image_type
    if pimms.is_str(image_type):
        image_type = image_type.lower()
        if image_type in image_types_by_name: return image_types_by_name[image_type]
        for it in image_types:
            if image_type in it.aliases(): return it
        raise ValueError('"%s" is not a valid image-type name or alias' % image_type)
    for x in (image_type, type(image_type)):
        try:    return image_types_by_image_type[x]
        except Exception: pass
        try:    return image_types_by_header_type[x]
        except Exception: pass
    raise ValueError('Unsupported image type: %s' % image_type)
866195
def open(self, fn):
        ""
        return open_image(fn, convert_mode=self.convert_mode, after_open=self.after_open)
42631
def is_valid_image(self, raw_data):
        
        buf = StringIO(raw_data)
        try:
            trial_image = Image.open(buf)
            trial_image.verify()
        except Exception:
            # TODO: Get more specific with this exception handling.
            return False
        return True
227268
def save(self, fn:PathOrStr):
        ""
        x = image2np(self.data*255).astype(np.uint8)
        PIL.Image.fromarray(x).save(fn)