Implementing Unsupervised Anomaly Detection with Halcon Deep Learning

  • No labeling requirements
  • Training uses only normal samples
  • Supports CPU-based training
  • Fast inference speeds

Best suited for projects with clearly visible defects. Note: Image dimensions should be multiples of 32 for optimal performance.

Performance Metrics

With recall at 92.1%, 7.9% of normal samples are falsely flagged as anomalies. Precision of 79.8% means 20.2% of detected anomalies are actually normal samples. The confusion matrix shows 47 false positives and 3 false negatives.


// Initialize environment
dev_update_off()
dev_close_window()
set_system('seed_rand', 25)

// Configuration parameters
imagePath := 'E:/dataset'
subfolders := ['normal','defective']
outputPath := imagePath+'/processed_data'
modelPath := imagePath+'/final_model.hdl'

// Model settings
resizeWidth := 320  // Must be 32x multiple
resizeHeight := 320
modelComplexity := 15
useGPU := true

// Create dataset structure
create_dict(datasetParams)
set_dict_tuple(datasetParams, 'image_sub_dirs', subfolders)
read_dl_dataset_anomaly(imagePath, [], [], [], datasetParams, dataset)

// Split dataset (60% train, 20% validation, 20% test)
split_dl_dataset(dataset, 60, 20, [])

// Initialize model
read_dl_model('base_anomaly_model.hdl', modelHandle)
set_dl_model_param(modelHandle, 'image_width', resizeWidth)
set_dl_model_param(modelHandle, 'image_height', resizeHeight)
set_dl_model_param(modelHandle, 'complexity', modelComplexity)
set_dl_model_param(modelHandle, 'runtime', 'gpu')

// Preprocessing setup
create_dict(preprocessConfig)
set_dict_tuple(preprocessConfig, 'overwrite_files', true)
create_dl_preprocess_param('anomaly_detection', resizeWidth, resizeHeight, 3, [], [], 'constant_values', 'full_domain', [], [], [], [], preprocessParams)
preprocess_dl_dataset(dataset, outputPath, preprocessParams, preprocessConfig, processedDataset)

// Training configuration
trainParams := []
set_dict_tuple(trainParams, 'regularization_noise', 0.01)
set_dict_tuple(trainParams, 'error_threshold', 0.001)
set_dict_tuple(trainParams, 'domain_ratio', 0.75)

create_dl_train_param(modelHandle, 15, [], true, 73, 'anomaly', trainParams, fullTrainParams)
train_dl_model(dataset, modelHandle, fullTrainParams, 0, results, trainInfo, evalInfo)

// Save trained model
write_dl_model(modelHandle, modelPath)

Model Evaluation


// Set evaluation threshold
set_dl_model_param(modelHandle, 'standard_deviation_factor', 1.0)

// Calculate thresholds
create_dict(thresholdParams)
set_dict_tuple(thresholdParams, 'enable_display', 'true')
compute_dl_anomaly_thresholds(modelHandle, dataset, thresholdParams, segThreshold, classThresholds)

// Performance assessment
create_dict(evalConfig)
set_dict_tuple(evalConfig, 'measures', 'all')
set_dict_tuple(evalConfig, 'anomaly_classification_thresholds', classThresholds)
evaluate_dl_model(dataset, modelHandle, 'split', 'test', evalConfig, evalResults, evalParams)

Inference Example


// Load saved model
read_dl_model(modelPath, loadedModel)

// Prepare test data
testFiles := []
list_files(imagePath+'/defective', ['files','follow_links','recursive'], testFiles)
tuple_regexp_select(testFiles, ['\\.(tif|tiff|gif|bmp|jpg|jpeg|jp2|png)$','ignore_case'], filteredFiles)

// Process test samples
create_dict(displayConfig)
for i := 0 to |filteredFiles| - 1 by 1
    read_image(testImg, filteredFiles[i])
    gen_dl_samples_from_images(testImg, sample)
    preprocess_dl_samples(sample, preprocessParams)
    apply_dl_model(loadedModel, sample, [], result)
    threshold_dl_anomaly_results(segThreshold, classThresholds[2], result)
endfor

Tags: Halcon Deep Learning anomaly detection Computer Vision Image Processing

Posted on Sat, 24 Oct 2026 16:20:02 +0000 by rishiraj