I want to calculate area of all polygon features using Field Geometry function of QGIS 3.22 version. But somehow it always gives an import QGIS error, but when I tried to do a simple buffer of a vector layer in same Jupyter Notebook environment it worked.
import time
from qgis.core import (
QgsApplication,
QgsVectorLayer,
QgsFields,
QgsField,
QgsFeature,
QgsGeometry,
QgsProject,
QgsVectorFileWriter,
)
import processing
def calculate_area_with_qgis(vector_layer_path, output_layer_path):
# Initialize QGIS application
QgsApplication.setPrefixPath("C:/Program Files/QGIS 3.22.5/apps/gis-ltr/qgiscrashhandler.exe", True)
os.environ['QGIS_PREFIX_PATH'] = 'C:/Program Files/QGIS 3.22.5'
QgsApplication.initQgis()
# Load the vector layer
vector_layer = QgsVectorLayer(vector_layer_path, "vector_layer", "ogr")
if not vector_layer.isValid():
print("Failed to load the vector layer")
return None
# Set up the field calculator parameters
parameters = {
'INPUT': vector_layer,
'FIELD_NAME': 'AREA',
'FIELD_TYPE': 0, # Double
'FIELD_LENGTH': 10,
'FIELD_PRECISION': 3,
'FORMULA': '$area',
'OUTPUT': output_layer_path
}
# Run the field calculator algorithm
start_time = time.time()
processing.run("native:fieldcalculator", parameters)
end_time = time.time()
elapsed_time = end_time - start_time
# Exit QGIS application
QgsApplication.exitQgis()
return elapsed_time
vector_layer_path = r"C:/Users/schakraborty/OneDrive - RMS/Desktop/INDUSTRIES/South Africa/Provinces/Kwaza_u_natul/Output/try_xyz/kwaza_natul_merged.shp"
output_layer_path = r"C:/Users/schakraborty/OneDrive - RMS/Desktop/INDUSTRIES/South Africa/Provinces/Kwaza_u_natul/Output/try_xyz/kwaza_natul_merged_area.shp"
elapsed_time = calculate_area_with_qgis(vector_layer_path, output_layer_path)
print(f"Elapsed time: {elapsed_time} seconds")
The error is coming as this -
ImportError Traceback (most recent call last)
Cell In[4], line 12
1 import time
2 from qgis.core import (
3 QgsApplication,
4 QgsVectorLayer,
(...)
10 QgsVectorFileWriter,
11 )
---> 12 import processing
14 def calculate_area_with_qgis(vector_layer_path, output_layer_path):
15 # Initialize QGIS application
16 QgsApplication.setPrefixPath("C:/Program Files/QGIS 3.22.5/apps/gis-ltr/qgiscrashhandler.exe", True)
File ~\AppData\Local\anaconda3\envs\testing1\Library\python\qgis\utils.py:888, in _import(name, globals, locals, fromlist, level)
884 _RemoveDllDirectory(_import_paths.pop(p))
886 _import_path = new_path
--> 888 mod = _builtin_import(name, globals, locals, fromlist, level)
890 if mod and getattr(mod, '__file__', None):
891 module_name = mod.__name__ if fromlist else name
File ~\AppData\Local\anaconda3\envs\testing1\Library\python\qgis\analysis\__init__.py:26
22 __copyright__ = '(C) 2014, Nathan Woodrow'
24 from qgis.PyQt import QtCore
---> 26 from qgis._analysis import *
28 # preserve API compatibility following QgsExifTools moved to core
29 from qgis.core import QgsExifTools
File ~\AppData\Local\anaconda3\envs\testing1\Library\python\qgis\utils.py:888, in _import(name, globals, locals, fromlist, level)
884 _RemoveDllDirectory(_import_paths.pop(p))
886 _import_path = new_path
--> 888 mod = _builtin_import(name, globals, locals, fromlist, level)
890 if mod and getattr(mod, '__file__', None):
891 module_name = mod.__name__ if fromlist else name
ImportError: DLL load failed while importing _analysis: The specified module could not be found.
from qgis.analysis import QgsNativeAlgorithms QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) reg = QgsApplication.processingRegistry() reg.algorithms()
This will add content to the registtry and you can find the processing algorithm. To cal the algorithm still need more steps to call the algorithm