I would like to assign the average of all raster pixels laying under a vector line as an attribute to the vector line. So the mean of the grey/white pixels to each of the red line segments in the following image:
I have found solutions to assign raster values to points and polygons link1 link2 link3, but not for lines. Here what I have tested so far:
To buffer the lines, calculate zonal statistics per buffer segment and join the attributes by location with the original lines. This seems quiet time-consuming.
To convert each pixel to a point and assign its value to the closest line using v.distance . Here, I haven't figures out, how to update the distance to a 'dist' column of my line layer. I will open a new question for this (link to question).
To apply the GRASS module v.rast.stats. With the following command, some values from the raster map were attached to the red lines. However this update only worked for a limited number of lines (yellow lines in image). I don't know why the raster information is not updated to all lines.
processing.runalg('grass7:v.rast.stats', {"map": red_lines, "raster": rlayer, "column_prefix": "ucm", "method": 'median', "GRASS_REGION_PARAMETER": "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax), "GRASS_OUTPUT_TYPE_PARAMETER":3, "output": red_lines_update})
My main question is if I have overseen any more straight-forward way to solve this.