A faster convert that works directly with a specific raster
554339
public static void bufferedToGray(DataBufferInt buffer, WritableRaster src, GrayU8 dst) {
		int[] srcData = buffer.getData();

		byte[] data = dst.data;

		int srcStride = stride(src);
		int srcOffset = getOffset(src);


		//CONCURRENT_BELOW BoofConcurrency.loopFor(0, dst.height, y -> {
		for (int y = 0; y < dst.height; y++) {
			int indexSrc = srcOffset + y*srcStride;
			int indexDst = dst.startIndex + y * dst.stride;
			for (int x = 0; x < dst.width; x++) {

				int rgb = srcData[indexSrc++];

				int r = (rgb >>> 16) & 0xFF;
				int g = (rgb >>> 8) & 0xFF;
				int b = rgb & 0xFF;

				int ave = (r + g + b) / 3;

				data[indexDst++] = (byte) ave;
			}
		}
		//CONCURRENT_ABOVE });
	}
1162545
private Raster asByteRaster(final Raster raster, ColorModel colorModel) {
        switch (raster.getTransferType()) {
            case DataBuffer.TYPE_BYTE:
                return raster;
            case DataBuffer.TYPE_USHORT:
                return raster; // TODO: we handle ushort especially for now..
            case DataBuffer.TYPE_INT:
                final int bands = colorModel.getNumComponents();
                final DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();

                int w = raster.getWidth();
                int h = raster.getHeight();
                int size = buffer.getSize();

                return new Raster(
                        new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, w, h, bands, w * bands, createBandOffsets(colorModel)),
                        new DataBuffer(DataBuffer.TYPE_BYTE, size * bands) {
                    @Override
                    public int getElem(int bank, int i) {
                        int index = i / bands;
                        int shift = (i % bands) * 8;

                        return (buffer.getElem(index) >>> shift) & 0xFF;
                    }

                    @Override
                    public void setElem(int bank, int i, int val) {
                        throw new UnsupportedOperationException("Wrapped buffer is read-only");
                    }
                }, new Point()) {};
            default:
                throw new IllegalArgumentException(String.format("Raster type %d not supported", raster.getTransferType()));
        }
    }
1064129
function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
    // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
    // not the usual [0, 1]. If a command like setFillColor is used the src
    // values will already be within the correct range. However, if we are
    // converting an image we have to map the values to the correct range given
    // above.
    // Ls,as,bs <---> L*,a*,b* in the spec
    var Ls = src[srcOffset];
    var as = src[srcOffset + 1];
    var bs = src[srcOffset + 2];
    if (maxVal !== false) {
      Ls = decode(Ls, maxVal, 0, 100);
      as = decode(as, maxVal, cs.amin, cs.amax);
      bs = decode(bs, maxVal, cs.bmin, cs.bmax);
    }

    // Adjust limits of 'as' and 'bs'
    as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;
    bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;

    // Computes intermediate variables X,Y,Z as per spec
    var M = (Ls + 16) / 116;
    var L = M + (as / 500);
    var N = M - (bs / 200);

    var X = cs.XW * fn_g(L);
    var Y = cs.YW * fn_g(M);
    var Z = cs.ZW * fn_g(N);

    var r, g, b;
    // Using different conversions for D50 and D65 white points,
    // per http://www.color.org/srgb.pdf
    if (cs.ZW < 1) {
      // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
      r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;
      g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;
      b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;
    } else {
      // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
      r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
      g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
      b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;
    }
    // clamp color values to [0,1] range then convert to [0,255] range.
    dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;
    dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;
    dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;
  }
1264671
def from_rasters(cls, rasters, relative_to_vrt=True, destination_file=None, nodata=None, mask_band=None):
        """"""
        if isinstance(rasters, list):
            doc = raster_list_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
        else:
            doc = raster_collection_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
        filename = cls._save_to_destination_file(doc, destination_file)
        return GeoRaster2.open(filename)
43482
def _rts_from_ra(ra, tspan, labels, block=True):
    """"""
    def _convert(a, tspan, labels):
        from nsim import Timeseries
        return Timeseries(a, tspan, labels)
    return distob.call(
            _convert, ra, tspan, labels, prefer_local=False, block=block)
44600
private void computeDivUVD(GrayF32 u , GrayF32 v , GrayF32 psi ,
							   GrayF32 divU , GrayF32 divV , GrayF32 divD ) {

		final int stride = psi.stride;

		// compute the inside pixel
		for (int y = 1; y < psi.height-1; y++) {

			// index of the current pixel
			int index = y*stride + 1;

			for (int x = 1; x < psi.width-1; x++ , index++) {

				float psi_index = psi.data[index];

				float coef0 = 0.5f*(psi.data[index+1] + psi_index);
				float coef1 = 0.5f*(psi.data[index-1] + psi_index);
				float coef2 = 0.5f*(psi.data[index+stride] + psi_index);
				float coef3 = 0.5f*(psi.data[index-stride] + psi_index);

				float u_index = u.data[index];

				divU.data[index] = coef0*(u.data[index+1] - u_index) + coef1*(u.data[index-1] - u_index) +
								   coef2*(u.data[index+stride] - u_index) + coef3*(u.data[index-stride] - u_index);

				float v_index = v.data[index];

				divV.data[index] = coef0*(v.data[index+1] - v_index) + coef1*(v.data[index-1] - v_index) +
								   coef2*(v.data[index+stride] - v_index) + coef3*(v.data[index-stride] - v_index);

				divD.data[index] = coef0 + coef1 + coef2 + coef3;
			}
		}

		// handle the image borders
		for( int x = 0; x < psi.width; x++ ) {
			computeDivUVD_safe(x,0,u,v,psi,divU,divV,divD);
			computeDivUVD_safe(x,psi.height-1,u,v,psi,divU,divV,divD);
		}
		for( int y = 1; y < psi.height-1; y++ ) {
			computeDivUVD_safe(0,y,u,v,psi,divU,divV,divD);
			computeDivUVD_safe(psi.width-1,y,u,v,psi,divU,divV,divD);
		}
	}
59311
private void getMapRow( int currentrow, ByteBuffer rowdata, boolean iscompressed ) throws IOException, DataFormatException {
        // if (logger.isDebugEnabled())
        // {
        // logger.debug("ACCESSING THE FILE at row: " + currentrow +
        // ", rasterMapType = " + rasterMapType +
        // ", numberOfBytesPerValue = " + numberOfBytesPerValue +
        // ", iscompressed = " + iscompressed);
        // }

        if (iscompressed) {
            /* Compressed maps */
            if (rasterMapType == -2) {
                /* Compressed double map */
                readCompressedFPRowByNumber(rowdata, currentrow, addressesofrows, cellFile, numberOfBytesPerValue);
            } else if (rasterMapType == -1) {
                /* Compressed floating point map */
                readCompressedFPRowByNumber(rowdata, currentrow, addressesofrows, cellFile, numberOfBytesPerValue);
            } else if (rasterMapType > 0) {
                /* Compressed integer map */
                readCompressedIntegerRowByNumber(rowdata, currentrow, addressesofrows, cellFile);
            } else {
                // if (logger.isDebugEnabled())
                // logger.error("format not double nor float");
            }
        } else {
            if (rasterMapType < 0) {
                /* Uncompressed floating point map */
                readUncompressedFPRowByNumber(rowdata, currentrow, cellFile, numberOfBytesPerValue);
            } else if (rasterMapType > 0) {
                /* Uncompressed integer map */
                readUncompressedIntegerRowByNumber(rowdata, currentrow, cellFile);
            } else {
                // if (logger.isDebugEnabled())
                // logger.error("Unknown case, iscompressed=" + iscompressed
                // + ", compressed=" + compressed + ", rasterMapType="
                // + rasterMapType);
            }
        }
        return;
    }
1171091
def ddtohms(xsky,ysky,verbose=False,precision=6):
    
    xskyh = xsky /15.
    xskym = (xskyh - np.floor(xskyh)) * 60.
    xskys = (xskym - np.floor(xskym)) * 60.
    yskym = (np.abs(ysky) - np.floor(np.abs(ysky))) * 60.
    yskys = (yskym - np.floor(yskym)) * 60.

    fmt = "%."+repr(precision)+"f"
    if isinstance(xskyh,np.ndarray):
        rah,dech = [],[]
        for i in range(len(xskyh)):
            rastr = repr(int(xskyh[i]))+':'+repr(int(xskym[i]))+':'+fmt%(xskys[i])
            decstr = repr(int(ysky[i]))+':'+repr(int(yskym[i]))+':'+fmt%(yskys[i])
            rah.append(rastr)
            dech.append(decstr)
            if verbose:
                print('RA = ',rastr,', Dec = ',decstr)
    else:
        rastr = repr(int(xskyh))+':'+repr(int(xskym))+':'+fmt%(xskys)
        decstr = repr(int(ysky))+':'+repr(int(yskym))+':'+fmt%(yskys)
        rah = rastr
        dech = decstr
        if verbose:
            print('RA = ',rastr,', Dec = ',decstr)

    return rah,dech
604399
def _zdt_to_nanos(self, zdt):
        """"""
        instant = zdt.toInstant()
        return instant.getNano() + instant.getEpochSecond() * 1000000000
720390
def _as_rescale(self, get, targetbitdepth):
        """"""
        width, height, pixels, meta = get()
        maxval = 2**meta['bitdepth'] - 1
        targetmaxval = 2**targetbitdepth - 1
        factor = float(targetmaxval) / float(maxval)
        meta['bitdepth'] = targetbitdepth

        def iterscale(rows):
            for row in rows:
                yield array('BH'[targetbitdepth > 8],
                            [int(round(x * factor)) for x in row])
        if maxval == targetmaxval:
            return width, height, pixels, meta
        else:
            if 'transparent' in meta:
                transparent = meta['transparent']
                if isinstance(transparent, tuple):
                    transparent = tuple(list(
                                        iterscale((transparent,))
                                        )[0])
                else:
                    transparent = tuple(list(
                                        iterscale(((transparent,),))
                                        )[0])[0]
                meta['transparent'] = transparent
            return width, height, iterscale(pixels), meta
421707
def union(rasters):
    
    if sum([rasters[0].x_cell_size == i.x_cell_size for i in rasters]) == len(rasters) \
       and sum([rasters[0].y_cell_size == i.y_cell_size for i in rasters]) == len(rasters)\
       and sum([rasters[0].projection.ExportToProj4() == i.projection.ExportToProj4() for i in rasters]) == len(rasters):
        if sum([rasters[0].nodata_value == i.nodata_value for i in rasters]) == len(rasters):
            ndv = rasters[0].nodata_value
        else:
            ndv = np.nan
        if ndv == None:
            ndv = np.nan
        if sum([rasters[0].datatype == i.datatype for i in rasters]) == len(rasters):
            datatype = rasters[0].datatype
        else:
            datatype = None
        projection = rasters[0].projection
        lonmin = min([i.xmin for i in rasters])
        lonmax = max([i.xmax for i in rasters])
        latmin = min([i.ymin for i in rasters])
        latmax = max([i.ymax for i in rasters])
        shape = (np.abs(np.floor((latmax-latmin)/rasters[0].y_cell_size)).astype(int), np.floor((lonmax-lonmin)/rasters[0].x_cell_size).astype(int))
        out = ndv*np.ones(shape)
        outmask = np.ones(shape).astype(bool)
        for i in rasters:
            (row, col) = map_pixel(i.xmin, i.ymax, rasters[0].x_cell_size, rasters[0].y_cell_size, lonmin, latmax)
            out[row:row+i.shape[0], col:col+i.shape[1]] = np.where(i.raster.data != i.nodata_value, i.raster.data,\
                                                         out[row:row+i.shape[0], col:col+i.shape[1]])
            outmask[row:row+i.shape[0], col:col+i.shape[1]] = np.where(i.raster.mask == False, False,\
                                                         outmask[row:row+i.shape[0], col:col+i.shape[1]])
        out = np.ma.masked_array(out, mask=outmask, fill_value=ndv)
        return GeoRaster(out, (lonmin, rasters[0].x_cell_size, 0.0, latmax, 0.0, rasters[0].y_cell_size), nodata_value=ndv, projection=projection, datatype=datatype)
    else:
        raise RasterGeoError('Rasters need to have same pixel sizes. Use the aggregate or dissolve functions to generate correct GeoRasters')
209220
def convert(self):
        
        try:
            log('Processing %s ...' % self.rapid_output_file_list[0])
            time_start_conversion = datetime.utcnow()

            # Validate the raw netCDF file
            log('validating input netCDF file', 'INFO')
            id_len, time_len = self._validate_raw_nc()

            # Initialize the output file (create dimensions and variables)
            log('initializing output', 'INFO')
            self._initialize_output(time_len, id_len)

            self._generate_time_values()

            # copy river ids over
            self.cf_nc.variables[self.output_id_dim_name][:] = \
                self.raw_nc_list[0].get_river_id_array()

            # Populate comid, lat, lon, z
            log('writing comid lat lon z')
            lookup_start = datetime.now()
            self._write_comid_lat_lon_z()
            duration = str((datetime.now() - lookup_start).total_seconds())
            log('Lookup Duration (s): ' + duration)

            # Create a variable for streamflow. This is big, and slows down
            # previous steps if we do it earlier.
            self._copy_streamflow_values()

            # close files
            for raw_nc in self.raw_nc_list:
                raw_nc.close()
            self.cf_nc.close()

            # delete original RAPID output
            remove_files(*self.rapid_output_file_list)

            # rename nc compliant file to original name
            os.rename(self.cf_compliant_file, self.rapid_output_file_list[0])
            log('Time to process %s' %
                (datetime.utcnow()-time_start_conversion))
        except Exception:
            # delete cf RAPID output
            remove_files(self.cf_compliant_file)
            raise
864153
private BufferedImage to8Bit1ComponentGrayScale(int[][] decoded, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        byte[] imageBuffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

        for (int i = 0; i < imageBuffer.length; i++) {
            imageBuffer[i] = (byte) decoded[0][i];
        }

        return image;
    }
1188597
def resize_old(self, block_size, order=0, mode='constant', cval=False):
        '''
        
        '''
        if not cval:
            cval = np.nan
        if (self.raster.dtype.name.find('float') != -1 and
            np.max(np.abs([self.max(), self.min()])) > 1):
            raster2 = (self.raster-self.min())/(self.max()-self.min())
        else:
            raster2 = self.raster.copy()
        raster2 = raster2.astype(float)
        raster2[self.raster.mask] = np.nan
        raster2 = resize(raster2, block_size, order=order, mode=mode, cval=cval)
        raster2 = np.ma.masked_array(raster2, mask=np.isnan(raster2),
                                     fill_value=self.raster.fill_value)
        raster2 = raster2*(self.max()-self.min())+self.min()
        raster2[raster2.mask] = self.nodata_value
        raster2.mask = np.logical_or(np.isnan(raster2.data), raster2.data == self.nodata_value)
        geot = list(self.geot)
        [geot[-1], geot[1]] = np.array([geot[-1], geot[1]])*self.shape/block_size
        return GeoRaster(raster2, tuple(geot), nodata_value=self.nodata_value,\
                        projection=self.projection, datatype=self.datatype)
667336
def _rgbtomask(self, obj):
        """"""
        dat = obj.get_image().get_data()  # RGB arrays
        return dat.sum(axis=2).astype(np.bool)
307429
public static ByteBuffer convertImageData(BufferedImage bi) {
        DataBuffer buff = bi.getRaster().getDataBuffer();
        // ClassCastException thrown if buff not instanceof DataBufferByte because raster data is not necessarily bytes.
        // Convert the original buffered image to grayscale.
        if (!(buff instanceof DataBufferByte)) {
            BufferedImage grayscaleImage = ImageHelper.convertImageToGrayscale(bi);
            buff = grayscaleImage.getRaster().getDataBuffer();
        }
        byte[] pixelData = ((DataBufferByte) buff).getData();
        //        return ByteBuffer.wrap(pixelData);
        ByteBuffer buf = ByteBuffer.allocateDirect(pixelData.length);
        buf.order(ByteOrder.nativeOrder());
        buf.put(pixelData);
        ((Buffer) buf).flip();
        return buf;
    }
1199012
def get_raster_array(image):
    
    if isinstance(image, RGB):
        rgb = image.rgb
        data = np.dstack([np.flipud(rgb.dimension_values(d, flat=False))
                          for d in rgb.vdims])
    else:
        data = image.dimension_values(2, flat=False)
        if type(image) is Raster:
            data = data.T
        else:
            data = np.flipud(data)
    return data