I have a geotiff that I've generated the way I'd like it displayed in QGIS. When I load the image as a raster layer, however, it automatically re-scales the pixel brightness values, and the image doesn't display the way I'd like. When using the GUI, I can click on the layer, then properties. I go to the histogram tab and click calculate histogram, then change the max to 255 (its typically a much smaller value to start, which makes the image look very "washed out"), and the image looks like I want it to..
I'm not sure why it changes it in the first place, but the same thing happens when I add the geotiff as a raster layer via my Python plugin. However, I can't figure out how to automate this via PyQGIS.. I'm using QGIS version 2.8.6-Wien..
If its important, I make the gtif prior to using QGIS via gdal_translate..
The question is - how can I use PyQGIS to perform this operation so the user doesn't have to do it? I have PyQGIS automatically adding the raster layer to the project already, its just the forcing it to display the full range of pixel values (within PyQGIS) that I am struggling with right now..
Also - its a 1 band image with a 'singlebandgray' renderer.
Update: the accepted answer pointed to a solution, but for the benefit of others who may be looking for a more direct answer to this particular issue, here is the code as modified to solve my issue:
newRasterLayer = QgsRasterLayer(gtifPathToFname, gtifFnameNoExten)
newRasterLayerProvider = newRasterLayer.dataProvider()
#Force 0 to map to black and 255 to map to white
#Note, this is for a single-band image, so only doing band 0
colorMapList = [QgsColorRampShader.ColorRampItem(0, QColor('#000000')), QgsColorRampShader.ColorRampItem(255, QColor('#FFFFFF'))]
#Jump through some hoops to get the colormap list defined above to
#be used by the new layer's renderer before it is added..
rasterShader = QgsRasterShader()
colorRamp = QgsColorRampShader()
colorRamp.setColorRampItemList(colorMapList)
colorRamp.setColorRampType(QgsColorRampShader.INTERPOLATED)
rasterShader.setRasterShaderFunction(colorRamp)
pseudoRenderer = QgsSingleBandPseudoColorRenderer(newRasterLayer.dataProvider(), newRasterLayer.type(), rasterShader)
newRasterLayer.setRenderer(pseudoRenderer)