0

I created a script to loop through the Clip Raster By Mask function.

I assign my personal files to the variables and use a nested for loop to iterate through the feature ID numbers in my selected shapefile. This will export a single image for each feature in my shapefile and save it in a folder with the name of each image corresponding to it's feature ID number. It works the way I want it to. The problem is it only works sometimes (maybe 20%) and is very weak when it does work. I can not do anything else on my computer if it starts working correctly. How can I strengthen this script and get it to work 100% or point me in the direction of the problem.

    import os

    layer = qgis.utils.iface.activeLayer()
    input_imagery = '-imagery I'm referencing-'
    input_shape = 'shapefile I'm referecncin-'
    dir_name = '-path to saved file-'
    format = 'tif'

    for format_number in range(283500, 401807):
         base_filename = str(format_number)
         output_file = os.path.join(dir_name, base_filename + "." + format)
         layer.selectByExpression(" \"TARGET_FID\" = '{}' 
    ".format(format_number))
         print(format_number)
         for feat in layer.getFeatures(" \"TARGET_FID\" = '{}' 
    ".format(format_number)):
             processing.run("gdal:cliprasterbymasklayer", {'INPUT' : 
    'input_imagery',
                'MASK' : QgsProcessingFeatureSourceDefinition(input_shape, True),
                'NODATA' : None,
                'ALPHA_BAND' : True,
                'CROP_TO_CUTLINE' : True,
                'KEEP_RESOLUTION' : True,
                'OPTIONS' : '',
                'DATA_TYPE' : 0,
                'OUTPUT' : output_file})         
             print('photo_saved')
  • Please Edit the question to contain the code as ASCII text. – Vince Jan 9 at 16:53

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.