Internal helper for saving a NumPy image array
493386
def _save_image(image, filename, return_img=None):
        """"""
        if not image.size:
            raise Exception('Empty image.  Have you run plot() first?')

        # write screenshot to file
        if isinstance(filename, str):
            if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename):
                filename = os.path.join(vtki.FIGURE_PATH, filename)
            if not return_img:
                return imageio.imwrite(filename, image)
            imageio.imwrite(filename, image)

        return image
1372570
def from_image_to_file(img_path, file_path):
    
    img = Image.open(img_path)
    data = numpy.array(img)
    data = numpy.reshape(data, len(img.getdata()) * 3)
    to_remove = data[len(data) - 1]
    data = numpy.delete(data, xrange(len(data) - to_remove, len(data)))
    data.tofile(file_path)
43733
def serialize_ndarray_readable(o):
    
    return dict(
        _type='np.ndarray',
        dtype=o.dtype,
        value=hint_tuples(o.tolist()))
875037
def _internal_write(out_stream, arr):
    

    if arr.size == 0:
        raise FormatError('Cannot encode empty array.')

    try:
        type_byte, struct_lib_type = _DATA_TYPES_NUMPY[str(arr.dtype)]
    except KeyError:
        raise FormatError('numpy ndarray type not supported by IDX format.')

    if arr.ndim > _MAX_IDX_DIMENSIONS:
        raise FormatError(
            'IDX format cannot encode array with dimensions > 255')

    if max(arr.shape) > _MAX_AXIS_LENGTH:
        raise FormatError('IDX format cannot encode array with more than ' +
                          str(_MAX_AXIS_LENGTH) + ' elements along any axis')

    # Write magic number
    out_stream.write(struct.pack('BBBB', 0, 0, type_byte, arr.ndim))

    # Write array dimensions
    out_stream.write(struct.pack('>' + 'I' * arr.ndim, *arr.shape))

    # Horrible hack to deal with horrible bug when using struct.pack to encode
    # unsigned ints in 2.7 and lower, see http://bugs.python.org/issue2263
    if sys.version_info < (2, 7) and str(arr.dtype) == 'uint8':
        arr_as_list = [int(i) for i in arr.reshape(-1)]
        out_stream.write(struct.pack('>' + struct_lib_type * arr.size,
                                     *arr_as_list))
    else:
        # Write array contents - note that the limit to number of arguments
        # doesn't apply to unrolled arguments
        out_stream.write(struct.pack('>' + struct_lib_type * arr.size,
                                     *arr.reshape(-1)))
36769
def image2array(image):
    
    nx, ny = image.shape  # find the size of the array
    imgh = np.reshape(image, nx*ny)  # change the shape to be 1d
    return imgh
57952
def _array2image_list(self, array):
        
        image_list = []
        k = 0
        for i in range(self._num_bands):
            if self._compute_bool[i] is True:
                num_data = self.num_response_list[i]
                array_i = array[k:k + num_data]
                image_i = self._imageModel_list[i].ImageNumerics.array2image(array_i)
                image_list.append(image_i)
                k += num_data
        return image_list
877476
def dump_img(fname):
    
    img = Image.open(fname)
    width, _ = img.size
    txt = ''
    pixels = list(img.getdata())
    for col in range(width):
        txt += str(pixels[col:col+width])
    return txt
557674
def save_png(opts = {})
      range = Args::CardRange.new(opts[:range], deck_size: size)
      batch = Args::SaveBatch.new.load!(opts, expand_by: size, layout: layout, dpi: dpi)
      @progress_bar.start("Saving PNGs to #{batch.summary}", size) do |bar|
        range.each do |i|
          @cards[i].save_png(batch[i])
          bar.increment
        end
      end
    end
1310630
def _make_image(tensor):
    """"""
    assert isinstance(tensor, NDArray)
    if Image is None:
        raise ImportError('need to install PIL for visualizing images')
    height, width, channel = tensor.shape
    tensor = _make_numpy_array(tensor)
    image = Image.fromarray(tensor)
    output = io.BytesIO()
    image.save(output, format='PNG')
    image_string = output.getvalue()
    output.close()
    return Summary.Image(height=height, width=width, colorspace=channel,
                         encoded_image_string=image_string)
1178460
def image2array(self, image):
        
        idex_mask = self._idex_mask
        array = util.image2array(image)
        if self._idex_mask_bool is True:
            return array[idex_mask == 1]
        else:
            return array
1240965
def _prepare_src_array(source_array, dtype):
    
    if not isinstance(source_array, NDArray) and not isinstance(source_array, np.ndarray):
        try:
            source_array = np.array(source_array, dtype=dtype)
        except:
            raise TypeError('values must be array like object')
    return source_array
1083340
def save_intermediate_array(self, array, name):
        """"""
        if self.intermediate_results:
            fits.writeto(name, array, overwrite=True)
428254
def from_array(array):
        
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from pytgbot.api_types.sendable.files import InputFile


        data = {}
        # 'type' is given by class type
        data['media'] = u(array.get('media'))
        if array.get('thumb') is None:
            data['thumb'] = None
        elif isinstance(array.get('thumb'), InputFile):
            data['thumb'] = None  # will be filled later by get_request_data()
        elif isinstance(array.get('thumb'), str):
            data['thumb'] = u(array.get('thumb'))
        else:
            raise TypeError('Unknown type, must be one of InputFile, str or None.')
        # end if
        data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None
        data['parse_mode'] = u(array.get('parse_mode')) if array.get('parse_mode') is not None else None

        instance = InputMediaDocument(**data)
        instance._raw = array
        return instance
1037107
def imgAverage(images, copy=True):
    '''
    
    '''
    i0 = images[0]
    out = imread(i0, dtype='float')
    if copy and id(i0) == id(out):
        out = out.copy()

    for i in images[1:]:
        out += imread(i, dtype='float')
    out /= len(images)
    return out
308534
def dump(self):
        """"""
        scan_lines = bytearray()
        for y in range(self.height):
            scan_lines.append(0)  # filter type 0 (None)
            scan_lines.extend(
                self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
            )
        # image represented as RGBA tuples, no interlacing
        return SIGNATURE + \
            self.pack_chunk(b'IHDR', struct.pack(b"!2I5B",
                                                 self.width, self.height,
                                                 8, 6, 0, 0, 0)) + \
            self.pack_chunk(b'IDAT', zlib.compress(bytes(scan_lines), 9)) + \
            self.pack_chunk(b'IEND', b'')
1075946
def array_to_img(x, scale=True):
    
    from PIL import Image
    if x.ndim != 3:
        raise Exception('Unsupported shape : ', str(x.shape), '. Need (channels, width, height)')
    if scale:
        x += max(-np.min(x), 0)
        x /= np.max(x)
        x *= 255
    if x.shape[0] == 3:
        # RGB
        if x.dtype != 'uint8':
            x = x.astype('uint8')
        return Image.fromarray(x.astype('uint8'), 'RGB')
    elif x.shape[0] == 1:
        # grayscale
        if x.dtype != 'uint8':
            x = x.astype('uint8')
        return Image.fromarray(x.reshape(x.shape[1], x.shape[2]), 'L')
    else:
        raise Exception('Unsupported channel number: ', x.shape[0])
1209224
def _write_image_data(im, id):
    
    im = im* (1.0/3000)
    # Create text
    lines = [   "ObjectType = Image",
                "NDims = <ndim>",
                "BinaryData = True",
                "BinaryDataByteOrderMSB = False",
                "CompressedData = False",
                #"TransformMatrix = <transmatrix>",
                "Offset = <origin>",
                "CenterOfRotation = <centrot>",
                "ElementSpacing = <sampling>",
                "DimSize = <shape>",
                "ElementType = <dtype>",
                "ElementDataFile = <fname>",
                "" ]
    text = '\n'.join(lines)
    
    # Determine file names
    tempdir = get_tempdir()
    fname_raw_ = 'im%i.raw' % id
    fname_raw = os.path.join(tempdir, fname_raw_)
    fname_mhd = os.path.join(tempdir, 'im%i.mhd' % id)
    
    # Get shape, sampling and origin
    shape = im.shape
    if hasattr(im, 'sampling'): sampling = im.sampling
    else: sampling = [1 for s in im.shape]
    if hasattr(im, 'origin'): origin = im.origin
    else: origin = [0 for s in im.shape]
    
    # Make all shape stuff in x-y-z order and make it string
    shape = ' '.join([str(s) for s in reversed(shape)])
    sampling = ' '.join([str(s) for s in reversed(sampling)])
    origin = ' '.join([str(s) for s in reversed(origin)])
    
    # Get data type
    dtype_itk = DTYPE_NP2ITK.get(im.dtype.name, None)
    if dtype_itk is None:
        raise ValueError('Cannot convert data of this type: '+ str(im.dtype))
    
    # Set mhd text
    text = text.replace('<fname>', fname_raw_)
    text = text.replace('<ndim>', str(im.ndim))
    text = text.replace('<shape>', shape)
    text = text.replace('<sampling>', sampling)
    text = text.replace('<origin>', origin)
    text = text.replace('<dtype>', dtype_itk)
    text = text.replace('<centrot>', ' '.join(['0' for s in im.shape]))
    if im.ndim==2:
        text = text.replace('<transmatrix>', '1 0 0 1')
    elif im.ndim==3:
        text = text.replace('<transmatrix>', '1 0 0 0 1 0 0 0 1')
    elif im.ndim==4:
        pass # ???
    
    # Write data file
    f = open(fname_raw, 'wb')
    try:
        f.write(im.data)
    finally:
        f.close()
    
    # Write mhd file
    f = open(fname_mhd, 'wb')
    try:
        f.write(text.encode('utf-8'))
    finally:
        f.close()
    
    # Done, return path of mhd file
    return fname_mhd