Created
December 3, 2019 14:45
-
-
Save OterLabb/8cf2f736ff54e59fc5ec8cda2d1c0372 to your computer and use it in GitHub Desktop.
Render a folder with rasters to an rgb image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from qgis.core import QgsRasterLayer | |
from PyQt5.QtCore import QFileInfo | |
import os | |
maindir = r'G:\kulturminner\New Folder (18)\501ad5c3\slope2' | |
files = [x for x in os.listdir(maindir) if x.endswith(".tif")] | |
outFolder = os.path.join(maindir, 'rendered') | |
def StringToRaster(file, filepath): | |
# Check if string is provided | |
fileInfo = QFileInfo(filepath) | |
path = fileInfo.filePath() | |
baseName = fileInfo.baseName() | |
layer = QgsRasterLayer(path, baseName) | |
QgsProject.instance().addMapLayer(layer) | |
layer.loadNamedStyle(uri) | |
pipe = QgsRasterPipe() | |
renderer = layer.renderer() | |
provider=layer.dataProvider() | |
pipe.set(provider.clone()) | |
pipe.set(renderer.clone()) | |
extent = layer.extent() | |
width, height = layer.width(), layer.height() | |
crs = layer.crs().toWkt() | |
file_writer = QgsRasterFileWriter(os.path.join(outFolder, file)) | |
file_writer.writeRaster(pipe, | |
width, | |
height, | |
extent, | |
layer.crs()) | |
if layer.isValid() is True: | |
print ("Layer was loaded successfully!") | |
else: | |
print ("Unable to read basename and file path - Your string is probably invalid") | |
QgsProject.instance().removeAllMapLayers() # Remove all layers | |
# Symbology | |
uri = r"C:\Users\OterLabb\symb_slope.qml" | |
if not os.path.exists(outFolder): | |
os.makedirs(outFolder) | |
for file in files: | |
filepath = os.path.join(maindir, file) | |
print(filepath) | |
StringToRaster(file, filepath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment