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


		int numBands = src.getNumBands();

		int size = dst.getWidth() * dst.getHeight();

		int srcStride = stride(src);
		int srcOffset = getOffset(src);
		int srcStrideDiff = srcStride-src.getNumDataElements()*dst.width;

		if(BoofConcurrency.USE_CONCURRENT ) {
			if (numBands == 3) {
				ImplConvertRaster_MT.from_3BU8_to_U8(srcData, srcStride, srcOffset, dst);
			} else if (numBands == 1) {
				ImplConvertRaster_MT.from_1BU8_to_U8(srcData, size, srcStride, srcOffset, srcStrideDiff, dst);
			} else if (numBands == 4) {
				ImplConvertRaster_MT.from_4BU8_to_U8(srcData, srcStride, srcOffset, dst);
			} else {
				throw new RuntimeException("Unexpected number of bands found. Bands = " + numBands);
			}
		} else {
			if (numBands == 3) {
				ImplConvertRaster.from_3BU8_to_U8(srcData, srcStride, srcOffset, dst);
			} else if (numBands == 1) {
				ImplConvertRaster.from_1BU8_to_U8(srcData, size, srcStride, srcOffset, srcStrideDiff, dst);
			} else if (numBands == 4) {
				ImplConvertRaster.from_4BU8_to_U8(srcData, srcStride, srcOffset, dst);
			} else {
				throw new RuntimeException("Unexpected number of bands found. Bands = " + numBands);
			}
		}
	}
1144545
def convert(filepath, outfilepath):
    """"""

    logger = logging.getLogger("example1")
    logger.setLevel(logging.INFO)
    fmt = logging.Formatter(STD_FORMAT)
    stderrHdlr = logging.StreamHandler()
    stderrHdlr.setFormatter(fmt)
    logger.addHandler(stderrHdlr)

    fi = ImageViewCairo(logger)
    fi.configure(500, 1000)

    # Load fits file
    image = load_data(filepath, logger=logger)

    # Make any adjustments to the image that we want
    fi.set_bg(1.0, 1.0, 1.0)
    fi.set_image(image)
    fi.auto_levels()
    fi.zoom_fit()
    fi.center_image()

    ht_pts = 11.0 / point_in
    wd_pts = 8.5 / point_in
    off_x, off_y = 0, 0

    out_f = open(outfilepath, 'w')
    surface = cairo.PDFSurface(out_f, wd_pts, ht_pts)
    # set pixels per inch
    surface.set_fallback_resolution(300, 300)
    surface.set_device_offset(off_x, off_y)
    try:
        fi.save_image_as_surface(surface)
        surface.show_page()
        surface.flush()
        surface.finish()
    finally:
        out_f.close()
379414
public static InterleavedF32 convert( Planar<GrayF32> input , InterleavedF32 output ) {
		if (output == null) {
			output = new InterleavedF32(input.width, input.height,input.getNumBands());
		} else {
			output.reshape(input.width,input.height,input.getNumBands());
		}

		if( BoofConcurrency.USE_CONCURRENT ) {
			ImplConvertImage_MT.convert(input,output);
		} else {
			ImplConvertImage.convert(input,output);
		}

		return output;
	}
443155
def convert_from_sliced_object(data):
    """"""
    if data.base is not None and isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray):
        if not data.flags.c_contiguous:
            warnings.warn("Usage of np.ndarray subset (sliced data) is not recommended "
                          "due to it will double the peak memory cost in LightGBM.")
            return np.copy(data)
    return data
1338436
private byte[] convert(Bitmap bitmap, String format) {
        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();

        DataBuffer buffer = new DataBufferByte(bitmap.getPixels(), bitmap.getLength());
        WritableRaster writableRaster = Raster.createPackedRaster(buffer, width, height, width, MASKS, null);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        bufferedImage.setData(writableRaster);

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIO.write(bufferedImage, format, outputStream);
            outputStream.close();
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
1070527
def getRastersAsPngs(self, session, tableName, rasterIds, postGisRampString, rasterField='raster', rasterIdField='id',  cellSize=None, resampleMethod='NearestNeighbour'):
        
        # Validate
        VALID_RESAMPLE_METHODS = ('NearestNeighbour', 'Bilinear', 'Cubic', 'CubicSpline', 'Lanczos')

        # Validate
        if resampleMethod not in VALID_RESAMPLE_METHODS:
            print('RASTER CONVERSION ERROR: {0} is not a valid resampleMethod.'
                  ' Please use either {1}'.format(resampleMethod,
                                                  ', '.join(VALID_RESAMPLE_METHODS)))

        if cellSize is not None:
            if not self.isNumber(cellSize):
                raise ValueError('RASTER CONVERSION ERROR: cellSize must be a number or None.')

        # Convert raster ids into formatted string
        rasterIdsString = '({0})'.format(', '.join(rasterIds))

        if cellSize is not None:
            statement = '''
                        SELECT ST_AsPNG(ST_Transform(ST_ColorMap(ST_Rescale({0}, {5}, '{6}'), 1, '{4}'), 4326, 'Bilinear')) As png
                        FROM {1}
                        WHERE {2} IN {3};
                        '''.format(rasterField, tableName, rasterIdField, rasterIdsString, postGisRampString, cellSize,
                                   resampleMethod)
        else:
            statement = '''
                        SELECT ST_AsPNG(ST_Transform(ST_ColorMap({0}, 1, '{4}'), 4326, 'Bilinear')) As png
                        FROM {1}
                        WHERE {2} IN {3};
                        '''.format(rasterField, tableName, rasterIdField, rasterIdsString, postGisRampString)
        result = session.execute(statement)
        return result
690971
def to_24bit_gray(mat: np.ndarray):
    """"""
    return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2)
380406
public static void fastinverseDelta(int[] data) {
                int sz0 = data.length / 4 * 4;
                int i = 1;
                if (sz0 >= 4) {
                        int a = data[0];
                        for (; i < sz0 - 4; i += 4) {
                                a = data[i] += a;
                                a = data[i + 1] += a;
                                a = data[i + 2] += a;
                                a = data[i + 3] += a;
                        }
                }

                for (; i != data.length; ++i) {
                        data[i] += data[i - 1];
                }
        }
305813
def apply(self, func, *args, **kwargs):
        '''
        
        '''
        return func(self.raster, *args, **kwargs)
900841
def raster_to_asc(raster_f, asc_f):
        
        raster_r = RasterUtilClass.read_raster(raster_f)
        RasterUtilClass.write_asc_file(asc_f, raster_r.data, raster_r.nCols, raster_r.nRows,
                                       raster_r.geotrans, raster_r.noDataValue)
1270462
def grassAsciiRasterToWKB(cls, session, grassRasterPath, srid, noData=0):
        
        # Constants
        NUM_HEADER_LINES = 6

        # Defaults
        north = 0.0
        east = 0.0
        west = 0.0
        rows = 0
        columns = 0

        if grassRasterPath is not None:
            # If the path to the file is given, open the file and extract contents.
            with open(grassRasterPath, 'r') as f:
                rasterLines = f.readlines()
        else:
            print("RASTER LOAD ERROR: Must provide the path the raster.")
            raise

        # Extract the headers from the file and derive metadata
        for line in rasterLines[0:NUM_HEADER_LINES]:
            spline = line.split()

            if 'north' in spline[0].lower():
                north = float(spline[1])
            elif 'east' in spline[0].lower():
                east = float(spline[1])
            elif 'west' in spline[0].lower():
                west = float(spline[1])
            elif 'rows' in spline[0].lower():
                rows = int(spline[1])
            elif 'cols' in spline[0].lower():
                columns = int(spline[1])

        # Define raster metadata from headers
        width = columns
        height = rows
        upperLeftX = west
        upperLeftY = north
        cellSizeX = int(abs(west - east) / columns)
        cellSizeY = -1 * cellSizeX

        # Assemble the data array string
        dataArrayList = []

        for line in rasterLines[NUM_HEADER_LINES:len(rasterLines)]:
            dataArrayList.append('[{0}]'.format(', '.join(line.split())))

        dataArrayString = '[{0}]'.format(', '.join(dataArrayList))

        # Create well known binary raster
        wellKnownBinary = cls.makeSingleBandWKBRaster(session=session,
                                                      width=width, height=height,
                                                      upperLeftX=upperLeftX, upperLeftY=upperLeftY,
                                                      cellSizeX=cellSizeX, cellSizeY=cellSizeY,
                                                      skewX=0, skewY=0,
                                                      srid=srid,
                                                      dataArray=dataArrayString,
                                                      noDataValue=noData)

        return wellKnownBinary
1210953
def process_slice(self, b_rot90=None):
        '''
        
        '''
        if b_rot90:
            self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice)
        if self.func == 'invertIntensities':
            self.invert_slice_intensities()
1032203
def aggregate(self, block_size):
        '''
        
        '''
        raster2 = block_reduce(self.raster, block_size, func=np.ma.sum)
        geot = self.geot
        geot = (geot[0], block_size[0] * geot[1], geot[2], geot[3], geot[4],
                block_size[1] * geot[-1])
        return GeoRaster(raster2, geot, nodata_value=self.nodata_value,\
                        projection=self.projection, datatype=self.datatype)
650012
public static InterleavedS8 convert( Planar<GrayS8> input , InterleavedS8 output ) {
		if (output == null) {
			output = new InterleavedS8(input.width, input.height,input.getNumBands());
		} else {
			output.reshape(input.width,input.height,input.getNumBands());
		}

		if( BoofConcurrency.USE_CONCURRENT ) {
			ImplConvertImage_MT.convert(input,output);
		} else {
			ImplConvertImage.convert(input,output);
		}

		return output;
	}
866484
def cli(source_f, raster_f, output, verbose):
    
    with fiona.open(source_f, 'r') as source:
        source_driver = source.driver
        source_crs = source.crs
        sink_schema = source.schema.copy()

        source_geom = source.schema['geometry']
        if source_geom == 'Point':
            sink_schema['geometry'] = '3D Point'
        elif source_geom == 'LineString':
            sink_schema['geometry'] = '3D LineString'
        elif source_geom == '3D Point' or source_geom == '3D LineString':
            pass
        else:
            click.BadParameter("Source geometry type {} not implemented".format(source_geom))

        with rasterio.open(raster_f) as raster:
            if source_crs != raster.crs:
                click.BadParameter("Features and raster have different CRS.")
            if raster.count > 1:
                warnings.warn("Found {0} bands in {1}, expected a single band raster".format(raster.bands, raster_f))
            supported = ['int16', 'int32', 'float32', 'float64']
            if raster.dtypes[0] not in supported:
                warnings.warn("Found {0} type in {1}, expected one of {2}".format(raster.dtypes[0]), raster_f, supported)
            with fiona.open(
                output, 'w',
                driver=source_driver,
                crs=source_crs,
                schema=sink_schema) as sink:

                for feature in source:
                    try:
                        feature_z = drapery.drape(raster, feature)
                        sink.write({
                            'geometry': mapping(feature_z),
                            'properties': feature['properties'],
                        })
                    except Exception:
                        logging.exception("Error processing feature %s:", feature['id'])
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)
472944
def get_negative_dem(raw_dem, neg_dem):
        """"""
        origin = RasterUtilClass.read_raster(raw_dem)
        max_v = numpy.max(origin.data)
        temp = origin.data < 0
        neg = numpy.where(temp, origin.noDataValue, max_v - origin.data)
        RasterUtilClass.write_gtiff_file(neg_dem, origin.nRows, origin.nCols, neg, origin.geotrans,
                                         origin.srs, origin.noDataValue, origin.dataType)