You need to first initQgis so that the data providers are loaded:
from qgis.core import QgsApplication
QgsApplication.initQgis()
... your stuff here
The issue is that the renderer class is QgsCategorizedSymbolRendererV2 instead of QgsGraduatedSymbolRendererV2. So, I categorized next shapefile by FID field:
and identical code (Germán Carrillo' script ) was run at the Python Console of QGIS:
prefix = "'"
layer = iface.activeLayer()
attr = layer.rendererV2().classAttribute()
attrColor = 'color' # Name of the field to store colors
fieldIndex = layer.dataProvider().fieldNameIndex(attrColor)
attrFeatMap = {}
for cat in layer.rendererV2().categories():
expr = "\""+attr+"\"="+prefix+unicode(cat.value())+prefix
for f in layer.getFeatures(QgsFeatureRequest(QgsExpression(expr))):
attrMap = { fieldIndex : cat.symbol().color().name()}
attrFeatMap[ f.id() ] = attrMap
layer.dataProvider().changeAttributeValues( attrFeatMap )
As you can see at the next image, result was completely satisfactory (I am not getting any error):
Editing Note:
This is the code for Graduated Symbol Renderer:
layer = iface.activeLayer()
provider = layer.dataProvider()
renderer = layer.rendererV2()
feats = [ feat for feat in layer.getFeatures() ]
values = [ feat.attribute('FID') for feat in feats ] #change for 'NDVI' in case of NDVI field
n = len(feats)
color_feats = [ renderer.symbolForValue(value).color().name() for value in values ]
idx = layer.fieldNameIndex('color')
for i, feat in enumerate(feats):
new_values = {idx : color_feats[i]}
provider.changeAttributeValues({i:new_values})
After running it at the Python Console of QGIS, values at 'color' field were placed as expected.
By using 'NDVI' field it also works perfectly:
Best Answer
You could use the following to add a new field and determining its type: