You can do that directly in QGIS with Raster -> Conversion -> Translate (Convert Format). To test it, I used a Float64 (Sixty four bit floating point) raster (named test) loaded in the Map View of QGIS. To convert it to Byte (8 bit type), I named it first at the "output file space" as test_byte.tif and afterward, I click in the icon pencil of "Translate Window" to modify gdal_translate command to:
gdal_translate -ot Byte -of GTiff /home/zeito/proyectosR/test.tif /home/zeito/proyectosR/test_byte.tif
as in the following image:
After click in OK, it can be observed at the layer properties of test_byte.tif that this raster is "Eight bit unsigned integer":
Editing Note:
This code works (to change the data type) in my bash console (in Windows is necessary to use IDLE Python GUI):
from osgeo import gdal, osr
dataset = gdal.Open('tiznados_canoa.tif')
geotransform = dataset.GetGeoTransform()
prj=dataset.GetProjection()
values = dataset.ReadAsArray()
band = dataset.GetRasterBand(1)
#Get minimum and maximum values of raster
min = band.GetMinimum()
max = band.GetMaximum()
#if not exist minimum and maximum values
if min is None or max is None:
(min,max) = band.ComputeRasterMinMax(1)
print "Min=%.3f, Max=%.3f" % (min,max) #print minimum and maximum values
# Set output file
output_file = "out.tif"
# Create new GTiff (Byte type)
driver = gdal.GetDriverByName("GTiff")
dst_ds = driver.Create(output_file, band.XSize, band.YSize, 1, gdal.GDT_Byte)
print "rows = ", band.YSize, "columns = ", band.XSize
print "Executing..."
for i in range(band.YSize):
for j in range(band.XSize):
values[i][j]
dst_ds.GetRasterBand(1).WriteArray( values )
# top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
dst_ds.SetGeoTransform( [ geotransform[0], geotransform[1], 0, geotransform[3], 0, geotransform[5] ] )
# set projection of new raster
dst_ds.SetProjection( prj )
dataset = None
gdalinfo -stats
. 32 bit images often have data only on the lower end of the scale which make them look like totally black if they are viewed without stretching the histogram. Then you may need to find an equivalent to -scale option of gdal_translate gdal.org/gdal_translate.html for Python.