from qgis.core import QgsRasterLayer, QgsVectorLayer, QgsProject from qgis.analysis import QgsRasterCalculatorEntry, QgsRasterCalculator # Define the paths to your raster and shapefile raster_path = 'D:/PHD/výučba/Python/cvičenia/dmr100m.tif' shapefile_path = 'D:/PHD/výučba/Python/cvičenia/vrstvy_python/ke-kraj.shp' # Load the raster and shapefile layers raster_layer = QgsRasterLayer(raster_path, 'Raster') shapefile_layer = QgsVectorLayer(shapefile_path, 'Shapefile', 'ogr') # Check if the layers are loaded successfully if not raster_layer.isValid() or not shapefile_layer.isValid(): print('Failed to load the layers.') exit() # Set the extent of the raster layer to match the shapefile layer QgsProject.instance().addMapLayer(raster_layer) raster_layer.setExtent(shapefile_layer.extent()) # Create an output path for the clipped raster output_path = 'D:/PHD/výučba/Python/cvičenia/dmr100m_clip.tif' # Set up the raster calculator expression entries = [] raster = QgsRasterCalculatorEntry() raster.ref = 'raster@1' raster.raster = raster_layer raster.bandNumber = 1 entries.append(raster) # Set up the raster calculator parameters calc = QgsRasterCalculator('raster@1', output_path, 'GTiff', raster_layer.extent(), raster_layer.width(), raster_layer.height(), entries) calc.processCalculation() # Check if the clipping was successful if calc.lastError() != QgsRasterCalculator.NoError: print('Failed to clip the raster.') else: print('Raster clipped successfully. Output saved at:', output_path)