Convert a PNM file containing raw pixel data into a PNG file
        with the parameters set in the writer object.  Works for
        (binary) PGM, PPM, and PAM formats.
184098
def convert_pnm(self, infile, outfile):
        

        if self.interlace:
            pixels = array('B')
            pixels.fromfile(infile,
                            (self.bitdepth/8) * self.color_planes *
                            self.width * self.height)
            self.write_passes(outfile, self.array_scanlines_interlace(pixels))
        else:
            self.write_passes(outfile, self.file_scanlines(infile))
837953
def get_bytes_to_image_callback(image_dims=(224, 224)):
    """"""
    from keras.preprocessing import image
    import numpy as np
    from PIL import Image
    from io import BytesIO

    def preprocess_image_bytes(data_bytes):
        """Process image bytes for ImageNet."""
        try:
            img = Image.open(BytesIO(data_bytes))  # open image
        except OSError as e:
            raise ValueError('Please provide a raw image')
        img = img.resize(image_dims, Image.ANTIALIAS)  # model requires 224x224 pixels
        x = image.img_to_array(img)  # convert image to numpy array
        x = np.expand_dims(x, axis=0)  # model expects dim 0 to be iterable across images
        return x
    return preprocess_image_bytes
227268
def save(self, fn:PathOrStr):
        ""
        x = image2np(self.data*255).astype(np.uint8)
        PIL.Image.fromarray(x).save(fn)
555398
def encode_images_as_png(images):
  """"""
  if tf.executing_eagerly():
    for image in images:
      yield tf.image.encode_png(image).numpy()
  else:
    (height, width, channels) = images[0].shape
    with tf.Graph().as_default():
      image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels))
      encoded_image_t = tf.image.encode_png(image_t)
      with tf.Session() as sess:
        for image in images:
          enc_string = sess.run(encoded_image_t, feed_dict={image_t: image})
          yield enc_string
29498
def _fromfile(self, fh):
        """"""
        fh.seek(0)
        data = fh.read(4096)
        if (len(data) < 7) or not (b'0' < data[1:2] < b'8'):
            raise ValueError("Not a Netpbm file:\n%s" % data[:32])
        try:
            self._read_pam_header(data)
        except Exception:
            try:
                self._read_pnm_header(data)
            except Exception:
                raise ValueError("Not a Netpbm file:\n%s" % data[:32])
770076
def file_to_png(fp):
	
	import PIL.Image # pylint: disable=import-error
	with io.BytesIO() as dest:
		PIL.Image.open(fp).save(dest, "PNG", optimize=True)
		return dest.getvalue()
181094
public synchronized static File[] convertPdf2Png(File inputPdfFile) throws IOException {
        Path path = Files.createTempDirectory("tessimages");
        File imageDir = path.toFile();

        //get Ghostscript instance
        Ghostscript gs = Ghostscript.getInstance();

        //prepare Ghostscript interpreter parameters
        //refer to Ghostscript documentation for parameter usage
        List<String> gsArgs = new ArrayList<String>();
        gsArgs.add("-gs");
        gsArgs.add("-dNOPAUSE");
        gsArgs.add("-dQUIET");
        gsArgs.add("-dBATCH");
        gsArgs.add("-dSAFER");
        gsArgs.add("-sDEVICE=pnggray");
        gsArgs.add("-r300");
        gsArgs.add("-dGraphicsAlphaBits=4");
        gsArgs.add("-dTextAlphaBits=4");
        gsArgs.add("-sOutputFile=" + imageDir.getPath() + "/workingimage%04d.png");
        gsArgs.add(inputPdfFile.getPath());

        //execute and exit interpreter
        try {
            synchronized (gs) {
                gs.initialize(gsArgs.toArray(new String[0]));
                gs.exit();
            }
        } catch (UnsatisfiedLinkError e) {
            logger.error(e.getMessage());
            throw new RuntimeException(getMessage(e.getMessage()));
        } catch (NoClassDefFoundError e) {
            logger.error(e.getMessage());
            throw new RuntimeException(getMessage(e.getMessage()));
        } catch (GhostscriptException e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            if (imageDir.list().length == 0) {
                imageDir.delete();
            }

            //delete interpreter instance (safer)
            try {
                Ghostscript.deleteInstance();
            } catch (GhostscriptException e) {
                //nothing
            }
        }

        // find working files
        File[] workingFiles = imageDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().matches("workingimage\\d{4}\\.png$");
            }
        });

        Arrays.sort(workingFiles, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                return f1.getName().compareTo(f2.getName());
            }
        });

        return workingFiles;
    }
542014
def convert_images_to_pil(self, images, dither, nq=0, images_info=None):
        

        # Convert to PIL images
        images2 = []
        for im in images:
            if isinstance(im, Image.Image):
                images2.append(im)
            elif np and isinstance(im, np.ndarray):
                if im.ndim == 3 and im.shape[2] == 3:
                    im = Image.fromarray(im, 'RGB')
                elif im.ndim == 3 and im.shape[2] == 4:
                    # im = Image.fromarray(im[:,:,:3],'RGB')
                    self.transparency = True
                    im = Image.fromarray(im[:, :, :4], 'RGBA')
                elif im.ndim == 2:
                    im = Image.fromarray(im, 'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []
        if nq >= 1:
            # NeuQuant algorithm
            for im in images:
                im = im.convert("RGBA")  # NQ assumes RGBA
                nq_instance = NeuQuant(im, int(nq))  # Learn colors from image
                if dither:
                    im = im.convert("RGB").quantize(palette=nq_instance.palette_image(), colors=255)
                else:
                    im = nq_instance.quantize(im, colors=255)  # Use to quantize the image itself

                self.transparency = True  # since NQ assumes transparency
                if self.transparency:
                    alpha = im.split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)
        else:
            # for index,im in enumerate(images):
            for i in range(len(images)):
                im = images[i].convert('RGB').convert('P', palette=Image.ADAPTIVE, dither=dither, colors=255)
                if self.transparency:
                    alpha = images[i].split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)

        # Done
        return images2
1193952
def write(self, image, options, thumbnail):
        
        format_ = options['format']
        quality = options['quality']
        image_info = options.get('image_info', {})
        # additional non-default-value options:
        progressive = options.get('progressive', settings.THUMBNAIL_PROGRESSIVE)
        raw_data = self._get_raw_data(
            image, format_, quality,
            image_info=image_info,
            progressive=progressive
        )
        thumbnail.write(raw_data)
312665
def imagedatadict_to_ndarray(imdict):
    
    arr = imdict['Data']
    im = None
    if isinstance(arr, parse_dm3.array.array):
        im = numpy.asarray(arr, dtype=arr.typecode)
    elif isinstance(arr, parse_dm3.structarray):
        t = tuple(arr.typecodes)
        im = numpy.frombuffer(
            arr.raw_data,
            dtype=structarray_to_np_map[t])
    # print "Image has dmimagetype", imdict["DataType"], "numpy type is", im.dtype
    assert dm_image_dtypes[imdict["DataType"]][1] == im.dtype
    assert imdict['PixelDepth'] == im.dtype.itemsize
    im = im.reshape(imdict['Dimensions'][::-1])
    if imdict["DataType"] == 23:  # RGB
        im = im.view(numpy.uint8).reshape(im.shape + (-1, ))[..., :-1]  # strip A
        # NOTE: RGB -> BGR would be [:, :, ::-1]
    return im
699457
def generatePixmap(base64_data):
    
    import_qt(globals())
    
    binary_data = binascii.a2b_base64(base64_data)
    arr = QtCore.QByteArray.fromRawData(binary_data)
    img = QtGui.QImage.fromData(arr)
    return QtGui.QPixmap(img)
144709
def extract_data(filename, num_images):
  
  print('Extracting', filename)
  with gzip.open(filename) as bytestream:
    bytestream.read(16)
    buf = bytestream.read(IMAGE_SIZE * IMAGE_SIZE * num_images)
    data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
    data = (data - (PIXEL_DEPTH / 2.0)) / PIXEL_DEPTH
    data = data.reshape(num_images, IMAGE_SIZE, IMAGE_SIZE, 1)
    return data
657414
def PILTowx(pimg):
    ''''''
    from wx_loader import wx
    wimg = wx.EmptyImage(pimg.size[0], pimg.size[1])
    wimg.SetData(pimg.convert('RGB').tostring())
    return wimg
771641
def export(self, nidm_version, export_dir):
        

        if self.masked_median is None:
            grand_mean_file = self.file.path
            grand_mean_img = nib.load(grand_mean_file)
            grand_mean_data = grand_mean_img.get_data()
            grand_mean_data = np.ndarray.flatten(grand_mean_data)

            mask_img = nib.load(self.mask_file)
            mask_data = mask_img.get_data()
            mask_data = np.ndarray.flatten(mask_data)

            grand_mean_data_in_mask = grand_mean_data[mask_data > 0]
            self.masked_median = np.median(
                np.array(grand_mean_data_in_mask, dtype=float))

        self.add_attributes((
            (PROV['type'], self.type),
            (PROV['label'], self.label),
            (NIDM_MASKED_MEDIAN, self.masked_median),
            (NIDM_IN_COORDINATE_SPACE, self.coord_space.id))
        )
259924
def convert_thumbnail_to_pil(thumbnail, mode='RGB'):
    """"""
    from PIL import Image
    if thumbnail.fmt == 0:
        size = (thumbnail.width, thumbnail.height)
        stride = thumbnail.widthbytes
        return Image.frombytes('RGBX', size, thumbnail.data, 'raw', mode,
                                stride)
    elif thumbnail.fmt == 1:
        return Image.open(io.BytesIO(thumbnail.data))
    else:
        raise ValueError('Unknown thumbnail format %d' % (thumbnail.fmt))
713561
def process_png(data)
      type   = 'png'
      width  = 0
      height = 0
      x_dpi  = 96
      y_dpi  = 96

      offset = 8
      data_length = data.size

      # Search through the image data to read the height and width in th the
      # IHDR element. Also read the DPI in the pHYs element.
      while offset < data_length

        length = data[offset + 0, 4].unpack("N")[0]
        png_type   = data[offset + 4, 4].unpack("A4")[0]

        case png_type
        when "IHDR"
          width  = data[offset +  8, 4].unpack("N")[0]
          height = data[offset + 12, 4].unpack("N")[0]
        when "pHYs"
          x_ppu = data[offset +  8, 4].unpack("N")[0]
          y_ppu = data[offset + 12, 4].unpack("N")[0]
          units = data[offset + 16, 1].unpack("C")[0]

          if units == 1
            x_dpi = x_ppu * 0.0254
            y_dpi = y_ppu * 0.0254
          end
        end

        offset = offset + length + 12

        break if png_type == "IEND"
      end
      raise "#{filename}: no size data found in png image.\n" unless height

      [type, width, height, x_dpi, y_dpi]
    end
1230119
def _from_p(self, mode):
        """"""
        self._check_modes(("P", "PA"))

        if not self.palette:
            raise RuntimeError("Can't convert palettized image, missing palette.")
        pal = np.array(self.palette)
        pal = da.from_array(pal, chunks=pal.shape)

        if pal.shape[1] == 4:
            # colormap's alpha overrides data alpha
            mode = "RGBA"
            alpha = None
        elif self.mode.endswith("A"):
            # add a new/fake 'bands' dimension to the end
            alpha = self.data.sel(bands="A").data[..., None]
            mode = mode + "A" if not mode.endswith("A") else mode
        else:
            alpha = None

        flat_indexes = self.data.sel(bands='P').data.ravel().astype('int64')
        dim_sizes = ((key, val) for key, val in self.data.sizes.items() if key != 'bands')
        dims, new_shape = zip(*dim_sizes)
        dims = dims + ('bands',)
        new_shape = new_shape + (pal.shape[1],)
        new_data = pal[flat_indexes].reshape(new_shape)
        coords = dict(self.data.coords)
        coords["bands"] = list(mode)

        if alpha is not None:
            new_arr = da.concatenate((new_data, alpha), axis=-1)
            data = xr.DataArray(new_arr, coords=coords, attrs=self.data.attrs, dims=dims)
        else:
            data = xr.DataArray(new_data, coords=coords, attrs=self.data.attrs, dims=dims)

        return data