Convert stored pixel data to image data.

Store data in Uint8Array

@param {Image} image A Cornerstone Image Object
@returns {Uint8Array} The image data for use by the WebGL shader
@memberof WebGLRendering
966276
function storedPixelDataToImageData (image) {
  // Transfer image data to alpha channel of WebGL texture
  // Store data in Uint8Array
  const pixelData = image.getPixelData();
  const numberOfChannels = 2;
  const data = new Uint8Array(image.width * image.height * numberOfChannels);
  let offset = 0;

  for (let i = 0; i < pixelData.length; i++) {
    data[offset++] = pixelData[i];
    data[offset++] = pixelData[i] < 0 ? 0 : 1; // 0 For negative, 1 for positive
  }

  return data;
}
710883
public static BufferedImage convertImageToARGB( Image image ) {
		if ( image instanceof BufferedImage && ((BufferedImage)image).getType() == BufferedImage.TYPE_INT_ARGB )
			return (BufferedImage)image;
		BufferedImage p = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = p.createGraphics();
		g.drawImage( image, 0, 0, null );
		g.dispose();
		return p;
	}
462970
def _pixel_data(image):
    
    # Test for PIL.Image and numpy.ndarray without requiring that cv2 or PIL
    # are installed.
    if 'PIL.' in str(type(image)):
        pixels = image.tobytes()
        width, height = image.size
    elif 'numpy.ndarray' in str(type(image)):
        if 'uint8' != str(image.dtype):
            image = image.astype('uint8')
        try:
            pixels = image.tobytes()
        except AttributeError:
            # `numpy.ndarray.tobytes()` introduced in `numpy` 1.9.0 - use the
            # older `tostring` method.
            pixels = image.tostring()
        height, width = image.shape[:2]
    else:
        # image should be a tuple (pixels, width, height)
        pixels, width, height = image

        # Check dimensions
        if 0 != len(pixels) % (width * height):
            raise PyLibDMTXError(
                (
                    'Inconsistent dimensions: image data of {0} bytes is not '
                    'divisible by (width x height = {1})'
                ).format(len(pixels), (width * height))
            )

    # Compute bits-per-pixel
    bpp = 8 * len(pixels) // (width * height)
    if bpp not in _PACK_ORDER:
        raise PyLibDMTXError(
            'Unsupported bits-per-pixel: [{0}] Should be one of {1}'.format(
                bpp, sorted(_PACK_ORDER.keys())
            )
        )

    return pixels, width, height, bpp
116917
public Double[] getValues(GriddedTile griddedTile, BufferedImage image) {
		short[] pixelValues = getPixelValues(image);
		Double[] values = getValues(griddedTile, pixelValues);
		return values;
	}
853744
function getImageData(img, width) {
		var can, ctx, imgd, buf8, buf32, height;

		switch (typeOf(img)) {
			case "HTMLImageElement":
				can = document.createElement("canvas");
				can.width = img.naturalWidth;
				can.height = img.naturalHeight;
				ctx = can.getContext("2d");
				ctx.drawImage(img,0,0);
			case "Canvas":
			case "HTMLCanvasElement":
				can = can || img;
				ctx = ctx || can.getContext("2d");
			case "CanvasRenderingContext2D":
				ctx = ctx || img;
				can = can || ctx.canvas;
				imgd = ctx.getImageData(0, 0, can.width, can.height);
			case "ImageData":
				imgd = imgd || img;
				width = imgd.width;
				if (typeOf(imgd.data) == "CanvasPixelArray")
					buf8 = new Uint8Array(imgd.data);
				else
					buf8 = imgd.data;
			case "Array":
			case "CanvasPixelArray":
				buf8 = buf8 || new Uint8Array(img);
			case "Uint8Array":
			case "Uint8ClampedArray":
				buf8 = buf8 || img;
				buf32 = new Uint32Array(buf8.buffer);
			case "Uint32Array":
				buf32 = buf32 || img;
				buf8 = buf8 || new Uint8Array(buf32.buffer);
				width = width || buf32.length;
				height = buf32.length / width;
		}

		return {
			can: can,
			ctx: ctx,
			imgd: imgd,
			buf8: buf8,
			buf32: buf32,
			width: width,
			height: height,
		};
	}
1111249
private static byte[] getByteArray(BufferedImage image) {
    checkNotNull(image);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
      ImageIO.write(image, "png", stream);
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }

    return stream.toByteArray();
  }
1317877
function (image, old) {
        var data1 = old.data,
            data2 = image.data,
            w1 = old.width,
            w2 = image.width,
            px1 = old.globalOffset.x,
            py1 = old.globalOffset.y,
            px2 = image.globalOffset.x,
            py2 = image.globalOffset.y,
            b1 = old.bounds,
            b2 = image.bounds,
            px = Math.min(b1.minX + px1, b2.minX + px2), // global offset for new image (by min in bounds)
            py = Math.min(b1.minY + py1, b2.minY + py2),
            b = { // bounds for new image include all of the pixels [0,0,width,height] (reduce to bounds)
                minX: 0,
                minY: 0,
                maxX: Math.max(b1.maxX + px1, b2.maxX + px2) - px,
                maxY: Math.max(b1.maxY + py1, b2.maxY + py2) - py,
            },
            w = b.maxX + 1, // size for new image
            h = b.maxY + 1,
            i, j, k, k1, k2, len;

        var result = new Uint8Array(w * h);

        // copy all old image
        len = b1.maxX - b1.minX + 1;
        i = (py1 - py + b1.minY) * w + (px1 - px + b1.minX);
        k1 = b1.minY * w1 + b1.minX;
        k2 = b1.maxY * w1 + b1.minX + 1;
        // walk through rows (Y)
        for (k = k1; k < k2; k += w1) {
            result.set(data1.subarray(k, k + len), i); // copy row
            i += w;
        }

        // copy new image (only "black" pixels)
        len = b2.maxX - b2.minX + 1;
        i = (py2 - py + b2.minY) * w + (px2 - px + b2.minX);
        k1 = b2.minY * w2 + b2.minX;
        k2 = b2.maxY * w2 + b2.minX + 1;
        // walk through rows (Y)
        for (k = k1; k < k2; k += w2) {
            // walk through cols (X)
            for (j = 0; j < len; j++) {
                if (data2[k + j] === 1) result[i + j] = 1;
            }
            i += w;
        }

        return {
            data: result,
            width: w,
            height: h,
            bounds: b,
            globalOffset: {
                x: px,
                y: py,
            }
        };
    }
125319
void precomputeAngles(D image) {
		int savecIndex = 0;
		for (int y = 0; y < image.height; y++) {
			int pixelIndex = y*image.stride + image.startIndex;

			for (int x = 0; x < image.width; x++, pixelIndex++, savecIndex++ ) {
				float spacialDX = imageDerivX.getF(pixelIndex);
				float spacialDY = imageDerivY.getF(pixelIndex);

				savedAngle.data[savecIndex] = UtilAngle.domain2PI(Math.atan2(spacialDY,spacialDX));
				savedMagnitude.data[savecIndex] = (float)Math.sqrt(spacialDX*spacialDX + spacialDY*spacialDY);
			}
		}
	}
37829
function getPixelValues (pixelData) {
  let minPixelValue = Number.MAX_VALUE;
  let maxPixelValue = Number.MIN_VALUE;
  const len = pixelData.length;
  let pixel;

  for (let i = 0; i < len; i++) {
    pixel = pixelData[i];
    minPixelValue = minPixelValue < pixel ? minPixelValue : pixel;
    maxPixelValue = maxPixelValue > pixel ? maxPixelValue : pixel;
  }

  return {
    minPixelValue,
    maxPixelValue
  };
}
1125771
def from_array(x, frame='unspecified'):
        

        if not Image.can_convert(x):
            raise ValueError('Cannot convert array to an Image!')

        dtype = x.dtype
        height = x.shape[0]
        width = x.shape[1]
        channels = 1
        if len(x.shape) == 3:
            channels = x.shape[2]
        if dtype == np.uint8:
            if channels == 1:
                if np.any((x % BINARY_IM_MAX_VAL) > 0):
                    return GrayscaleImage(x, frame)
                return BinaryImage(x, frame)
            elif channels == 3:
                return ColorImage(x, frame)
            else:
                raise ValueError(
                    'No available image conversion for uint8 array with 2 channels')
        elif dtype == np.uint16:
            if channels != 1:
                raise ValueError(
                    'No available image conversion for uint16 array with 2 or 3 channels')
            return GrayscaleImage(x, frame)
        elif dtype == np.float32 or dtype == np.float64:
            if channels == 1:
                return DepthImage(x, frame)
            elif channels == 2:
                return GdImage(x, frame)
            elif channels == 3:
                logging.warning('Converting float array to uint8')
                return ColorImage(x.astype(np.uint8), frame)
            return RgbdImage(x, frame)
        else:
            raise ValueError(
                'Conversion for dtype %s not supported!' %
                (str(dtype)))
316038
def _image_to_data(img):
    
    # If the image is already encoded in Base64, we have nothing to do here
    if "src" not in img.attrs or img["src"].startswith("data:"):
        return
    elif re.match("https?://", img["src"]):
        img_data = _load_url(img["src"]).read()
    else:
        img_data = _load_file(img["src"]).read()
    img_type = imghdr.what("", img_data)
    img_b64 = base64.b64encode(img_data)
    src_data = "data:image/none;base64,"
    if img_type:
        src_data = "data:image/{};base64,{}".format(img_type, img_b64)
    img["src"] = src_data
641205
def _tile_image(self, data):
        
        image = Image.open(BytesIO(data))
        return image.convert('RGBA')
759960
protected static ByteBuffer getRgba(Image image) {
    int w = (int) image.width(), h = (int) image.height(), size = w * h;
    int[] rawPixels = new int[size];
    ByteBuffer pixels = ByteBuffer.allocateDirect(size * 4);
    pixels.order(ByteOrder.nativeOrder());
    IntBuffer rgba = pixels.asIntBuffer();
    image.getRgb(0, 0, w, h, rawPixels, 0, w);

    for (int i = 0; i < size; i++) {
      int argb = rawPixels[i];
      // Order is inverted because this is read as a byte array, and we store intel ints.
      rgba.put(i, ((argb >> 16) & 0x0ff) | (argb & 0x0ff00ff00) | ((argb & 0xff) << 16));
    }
    return pixels;
  }
1100351
public INDArray asMatrix(BufferedImage image) {
        if (channels == 3) {
            return toBgr(image);
        } else {
            image = scalingIfNeed(image, true);
            int w = image.getWidth();
            int h = image.getHeight();
            INDArray ret = Nd4j.create(h, w);

            for (int i = 0; i < h; i++) {
                for (int j = 0; j < w; j++) {
                    ret.putScalar(new int[]{i, j}, image.getRGB(j, i));
                }
            }
            return ret;
        }
    }
1332751
function (data, colorFunc, state) {
        var gradientPixels = this._gradientPixels;
        var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
        var color = [0, 0, 0, 0];
        var off = 0;
        for (var i = 0; i < 256; i++) {
            colorFunc[state](i / 255, true, color);
            pixelsSingleState[off++] = color[0];
            pixelsSingleState[off++] = color[1];
            pixelsSingleState[off++] = color[2];
            pixelsSingleState[off++] = color[3];
        }
        return pixelsSingleState;
    }
107254
function (image, checkBump) {
        var canvas = document.createElement('canvas');
        var width = canvas.width = image.width;
        var height = canvas.height = image.height;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, width, height);
        checkBump = checkBump || false;
        var srcData = ctx.getImageData(0, 0, width, height);
        var dstData = ctx.createImageData(width, height);
        for (var i = 0; i < srcData.data.length; i += 4) {
            if (checkBump) {
                var r = srcData.data[i];
                var g = srcData.data[i + 1];
                var b = srcData.data[i + 2];
                var diff = Math.abs(r - g) + Math.abs(g - b);
                if (diff > 20) {
                    console.warn('Given image is not a height map');
                    return image;
                }
            }
            // Modified from http://mrdoob.com/lab/javascript/height2normal/
            var x1, y1, x2, y2;
            if (i % (width * 4) === 0) {
                // left edge
                x1 = srcData.data[i];
                x2 = srcData.data[i + 4];
            }
            else if (i % (width * 4) === (width - 1) * 4) {
                // right edge
                x1 = srcData.data[i - 4];
                x2 = srcData.data[i];
            }
            else {
                x1 = srcData.data[i - 4];
                x2 = srcData.data[i + 4];
            }

            if (i < width * 4) {
                // top edge
                y1 = srcData.data[i];
                y2 = srcData.data[i + width * 4];
            }
            else if (i > width * (height - 1) * 4) {
                // bottom edge
                y1 = srcData.data[i - width * 4];
                y2 = srcData.data[i];
            }
            else {
                y1 = srcData.data[i - width * 4];
                y2 = srcData.data[i + width * 4];
            }

            dstData.data[i] = (x1 - x2) + 127;
            dstData.data[i + 1] = (y1 - y2) + 127;
            dstData.data[i + 2] = 255;
            dstData.data[i + 3] = 255;
        }
        ctx.putImageData(dstData, 0, 0);
        return canvas;
    }
39492
def set_data(self, image):
        
        data = np.asarray(image)
        if self._data is None or self._data.shape != data.shape:
            self._need_vertex_update = True
        self._data = data
        self._need_texture_upload = True