Dump image data object to vtkjs
432113
def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
    """"""
    if root is None:
        root = {}
    root['vtkClass'] = 'vtkImageData'
    container = root

    container['spacing'] = dataset.GetSpacing()
    container['origin'] = dataset.GetOrigin()
    container['extent'] = dataset.GetExtent()

    dump_all_arrays(dataset_dir, data_dir, dataset, container, compress)

    return root
1084020
def save_vlen(self, key, data):
        
        shape = (None,) + data[0].shape[:-1]
        try:
            dset = self[key]
        except KeyError:
            vdt = h5py.special_dtype(vlen=data[0].dtype)
            dset = create(self, key, vdt, shape, fillvalue=None)
        nbytes = dset.attrs.get('nbytes', 0)
        totlen = dset.attrs.get('totlen', 0)
        for i, val in enumerate(data):
            nbytes += val.nbytes
            totlen += len(val)
        length = len(dset)
        dset.resize((length + len(data),) + shape[1:])
        for i, arr in enumerate(data):
            dset[length + i] = arr
        dset.attrs['nbytes'] = nbytes
        dset.attrs['totlen'] = totlen
136373
def _generate_example(self, data_path, image_id):
    """"""
    image_filepath = os.path.join(
        data_path, "VOCdevkit/VOC2007/JPEGImages", "{}.jpg".format(image_id))
    annon_filepath = os.path.join(
        data_path, "VOCdevkit/VOC2007/Annotations", "{}.xml".format(image_id))

    def _get_example_objects():
      """Function to get all the objects from the annotation XML file."""
      with tf.io.gfile.GFile(annon_filepath, "r") as f:
        root = xml.etree.ElementTree.parse(f).getroot()

        size = root.find("size")
        width = float(size.find("width").text)
        height = float(size.find("height").text)

        for obj in root.findall("object"):
          # Get object's label name.
          label = obj.find("name").text.lower()
          # Get objects' pose name.
          pose = obj.find("pose").text.lower()
          is_truncated = (obj.find("truncated").text == "1")
          is_difficult = (obj.find("difficult").text == "1")
          bndbox = obj.find("bndbox")
          xmax = float(bndbox.find("xmax").text)
          xmin = float(bndbox.find("xmin").text)
          ymax = float(bndbox.find("ymax").text)
          ymin = float(bndbox.find("ymin").text)
          yield {
              "label": label,
              "pose": pose,
              "bbox": tfds.features.BBox(
                  ymin / height, xmin / width, ymax / height, xmax / width),
              "is_truncated": is_truncated,
              "is_difficult": is_difficult,
          }

    objects = list(_get_example_objects())
    # Use set() to remove duplicates
    labels = sorted(set(obj["label"] for obj in objects))
    labels_no_difficult = sorted(set(
        obj["label"] for obj in objects if obj["is_difficult"] == 0
    ))
    return {
        "image": image_filepath,
        "image/filename": image_id + ".jpg",
        "objects": objects,
        "labels": labels,
        "labels_no_difficult": labels_no_difficult,
    }
609514
function writeOptimizedImages(imageData) {
  return Promise.all(
    imageData.map(item =>
      pify(fs.writeFile)(item.path, item.data).then(() => item.path)
    )
  );
}
422443
function copyImageDataWithCanvas ( imageData ) {
	const canvas = new Canvas( imageData.width, imageData.height );
	const ctx = canvas.getContext( '2d' );
	ctx.putImageData( imageData, 0, 0 );
				
	return ctx.getImageData( 0, 0, imageData.width, imageData.height );
}
291747
function handleImageData(handler, xref, res, image) {
    if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
      // For natively supported jpegs send them to the main thread for decoding.
      var dict = image.dict;
      var colorSpace = dict.get('ColorSpace', 'CS');
      colorSpace = ColorSpace.parse(colorSpace, xref, res);
      var numComps = colorSpace.numComps;
      var decodePromise = handler.sendWithPromise('JpegDecode',
                                                  [image.getIR(), numComps]);
      return decodePromise.then(function (message) {
        var data = message.data;
        return new Stream(data, 0, data.length, image.dict);
      });
    } else {
      return Promise.resolve(image);
    }
  }
339120
function getTransformedLayerData(iCanvas, layer, rect) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = rect.width;
    canvas.height = rect.height;
    ctx.translate(-rect.x, -rect.y);
    transformLayer(ctx, iCanvas, layer);
    ctx.drawImage(layer.img, 0, 0);
    return ctx.getImageData(0, 0, rect.width, rect.height);
}
80158
function createFromData(data, container) {
  if (data === undefined) {
    return Promise.resolve([])
  }

  if (!(isObject(data) || Array.isArray(data))) {
    return Promise.reject(new Error('Invalid animation data'))
  }
  return Promise.resolve(create(data, container))
}
378562
def loadPolyData(filename):
    """"""
    if not os.path.exists(filename):
        colors.printc("~noentry Error in loadPolyData: Cannot find", filename, c=1)
        return None
    fl = filename.lower()
    if   fl.endswith(".vtk"):
        reader = vtk.vtkPolyDataReader()
    elif fl.endswith(".ply"):
        reader = vtk.vtkPLYReader()
    elif fl.endswith(".obj"):
        reader = vtk.vtkOBJReader()
    elif fl.endswith(".stl"):
        reader = vtk.vtkSTLReader()
    elif fl.endswith(".byu") or fl.endswith(".g"):
        reader = vtk.vtkBYUReader()
    elif fl.endswith(".vtp"):
        reader = vtk.vtkXMLPolyDataReader()
    elif fl.endswith(".vts"):
        reader = vtk.vtkXMLStructuredGridReader()
    elif fl.endswith(".vtu"):
        reader = vtk.vtkXMLUnstructuredGridReader()
    elif fl.endswith(".txt"):
        reader = vtk.vtkParticleReader()  # (x y z scalar)
    elif fl.endswith(".xyz"):
        reader = vtk.vtkParticleReader()
    else:
        reader = vtk.vtkDataReader()
    reader.SetFileName(filename)
    if fl.endswith(".vts"):  # structured grid
        reader.Update()
        gf = vtk.vtkStructuredGridGeometryFilter()
        gf.SetInputConnection(reader.GetOutputPort())
        gf.Update()
        poly = gf.GetOutput()
    elif fl.endswith(".vtu"):  # unstructured grid
        reader.Update()
        gf = vtk.vtkGeometryFilter()
        gf.SetInputConnection(reader.GetOutputPort())
        gf.Update()
        poly = gf.GetOutput()
    else:
        try:
            reader.Update()
            poly = reader.GetOutput()
        except:
            poly = None

    if not poly:
        return None

    cleanpd = vtk.vtkCleanPolyData()
    cleanpd.SetInputData(poly)
    cleanpd.Update()
    return cleanpd.GetOutput()
1254636
def save_img(object, handle, **kwargs):
    """"""

    if isinstance(object, np.ndarray):
        normalized = _normalize_array(object)
        object = PIL.Image.fromarray(normalized)

    if isinstance(object, PIL.Image.Image):
        object.save(handle, **kwargs)  # will infer format from handle's url ext.
    else:
        raise ValueError("Can only save_img for numpy arrays or PIL.Images!")
1238135
function getImageData(diagram, type) {
    // Make a new canvas element for making image data
    var canvasElement = new Canvas(500, 500, type),
        canvas        = new mdjson.Graphics.Canvas(canvasElement.getContext("2d")),
        boundingBox   = diagram.getBoundingBox(canvas),
        rectExpand    = 10;

    // Initialize new canvas
    boundingBox.expand(rectExpand);
    canvas.origin = new mdjson.Graphics.Point(-boundingBox.x1, -boundingBox.y1);
    canvas.zoomFactor = new mdjson.Graphics.ZoomFactor(1, 1);
    canvasElement.width = boundingBox.getWidth();
    canvasElement.height = boundingBox.getHeight();

    // Draw diagram to the new canvas
    diagram.drawDiagram(canvas);
    return canvasElement.toBuffer();
}
673175
def image_to_data(image,
                  lang=None,
                  config='',
                  nice=0,
                  output_type=Output.STRING):
    '''
    
    '''

    if get_tesseract_version() < '3.05':
        raise TSVNotSupported()

    config = '{} {}'.format('-c tessedit_create_tsv=1', config.strip()).strip()
    args = [image, 'tsv', lang, config, nice]

    return {
        Output.BYTES: lambda: run_and_get_output(*(args + [True])),
        Output.DATAFRAME: lambda: get_pandas_output(args + [True]),
        Output.DICT: lambda: file_to_dict(run_and_get_output(*args), '\t', -1),
        Output.STRING: lambda: run_and_get_output(*args),
    }[output_type]()
1253527
def dump(obj, fp, **kwargs):
    """"""
    kwargs['default'] = serialize
    return json.dump(obj, fp, **kwargs)
848927
def dump(self, obj, context=None):
        """"""
        return self.schema_class(context=context).dump(obj).data
556316
def dump_data_array(dataset_dir, data_dir, array, root=None, compress=True):
    """"""
    if root is None:
        root = {}
    if not array:
        return None

    if array.GetDataType() == 12:
        # IdType need to be converted to Uint32
        array_size = array.GetNumberOfTuples() * array.GetNumberOfComponents()
        new_array = vtk.vtkTypeUInt32Array()
        new_array.SetNumberOfTuples(array_size)
        for i in range(array_size):
            new_array.SetValue(i, -1 if array.GetValue(i) <
                              0 else array.GetValue(i))
        pbuffer = memoryview(new_array)
    else:
        pbuffer = memoryview(array)

    pMd5 = hashlib.md5(pbuffer).hexdigest()
    ppath = os.path.join(data_dir, pMd5)
    with open(ppath, 'wb') as f:
        f.write(pbuffer)

    if compress:
        with open(ppath, 'rb') as f_in, gzip.open(os.path.join(data_dir, pMd5 + '.gz'), 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
        # Close then remove.
        os.remove(ppath)

    root['ref'] = get_ref(os.path.relpath(data_dir, dataset_dir), pMd5)
    root['vtkClass'] = 'vtkDataArray'
    root['name'] = array.GetName()
    root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
    root['numberOfComponents'] = array.GetNumberOfComponents()
    root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
    root['ranges'] = []
    if root['numberOfComponents'] > 1:
        for i in range(root['numberOfComponents']):
            root['ranges'].append(get_range_info(array, i))
        root['ranges'].append(get_range_info(array, -1))
    else:
        root['ranges'].append(get_range_info(array, 0))

    return root
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
1290038
def dump(obj, fp, **kwargs):
    
    return json.dump(obj, fp, cls=BioCJSONEncoder, **kwargs)